private void button1_Click(object sender, EventArgs e) { try { int port = 2000; string host = '192.168.0.127'; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 c = null; c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket c.Connect(ipe);//连接到服务器 } catch (ArgumentNullException a) { MessageBox.Show(String.Format('ArgumentNullException:{0}', a)); } catch (SocketException a) { MessageBox.Show(String.Format('SocketException:{0}', a.Message)); } } 发送数据代码 private void button2_Click(object sender, EventArgs e) { string sendStr = 'hello!This is a socket test'; byte[] bs = Encoding.ASCII.GetBytes(sendStr); c.Send(bs, bs.Length, 0);//发送测试信息 string recvStr = ''; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息 if (bytes <= 0) return; recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes); if(recvStr!='') { richTextBox1.Text += '有数据!\r\n'; richTextBox1.ScrollToCaret(); } else { } Thread.Sleep(100); |
|
来自: lkwenp2lm7anyq > 《JAVA》