示例#1
0
文件: UDP.cs 项目: jiehuali/CrossTalk
        public static UdpUser ConnectTo(string hostname, int port)
        {
            UdpUser connection = new UdpUser();

            connection.Client.AllowNatTraversal(true);
            try
            {
                connection.Client.Connect(hostname, port);
            }
            catch (System.Net.Sockets.SocketException e)
            {
                MessageBox.Show(e.Message, "SOCKET ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
            return(connection);
        }
示例#2
0
        private void ConnectToServer(object sender, EventArgs e)
        {
            if (connected)
            {
                disconnectFromServer();
            }
            else
            {
                client = UdpUser.ConnectTo(serverAddr.Text, 32123);

                if (client != null)
                {
                    client.Send(Encoding.ASCII.GetBytes("HLO" + GUID));

                    Thread.Sleep(100);

                    // SEND AUDIO FORMAT REQUEST
                    byte[] cmd = GetCmdBytes(CMDS.SetClientAudioFormat, (byte)audioFormatSelector.SelectedIndex);
                    client.Send(cmd);

                    // STORE IP ADDRESS
                    StoreSetting("server_ip", serverAddr.Text);


                    //wait for reply messages from server and send them to console
                    udpReceiveTaskToken = new CancellationTokenSource();
                    Task.Factory.StartNew(async() =>
                    {
                        while (true)
                        {
                            try
                            {
                                Received received = await client.Receive();

                                ClientReceivedData(received.Payload, received.Sender);
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(ex.ToString());
                            }
                        }
                    });
                }
            }
        }