private void btnStart_Click(object sender, EventArgs e)//设置目标IP(Client),本地IP(Server) { try { if (protocol == "UDP Server") { aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); RecUdpClient = new UdpClient(new IPEndPoint(ip, Convert.ToInt32(txtPort.Text))); MessageBox.Show("UDP Server创建成功"); Thread thReceive = new Thread(USReceive); thReceive.IsBackground = true; thReceive.Start(); } else if (protocol == "UDP Client")//UPD客户端,目标IP和端口 调用Socket.SendTo { aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//建立通信的Socket ip = IPAddress.Parse(txtIP.Text); point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text)); MessageBox.Show("UDP Client设置成功"); Thread thReceive = new Thread(UCReceive); thReceive.IsBackground = true; thReceive.Start(); } else if (protocol == "TCP Server") { mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//绑定端口号 mySocket.Bind(point);//绑定监听端口 MessageBox.Show("TCP Server绑定成功"); mySocket.Listen(10);//等待连接是一个阻塞过程,创建线程来监听 Thread thReceive = new Thread(TSReceive); thReceive.IsBackground = true; thReceive.Start(); } else if (protocol == "TCP Client") { ip = IPAddress.Parse(txtIP.Text);//目标IP point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//目标端口 aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); aimSocket.Connect(point);//连接服务器 MessageBox.Show("连接成功"); Thread thReceive = new Thread(TCReceive); thReceive.IsBackground = true; thReceive.Start(); } } catch {} }
评论