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和端口轉(zhuǎn)化為IPEndPoint實(shí)例 c = null; c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創(chuàng)建一個(gè)Socket c.Connect(ipe);//連接到服務(wù)器 } catch (ArgumentNullException a) { MessageBox.Show(String.Format('ArgumentNullException:{0}', a)); } catch (SocketException a) { MessageBox.Show(String.Format('SocketException:{0}', a.Message)); } } 發(fā)送數(shù)據(jù)代碼 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);//發(fā)送測試信息 string recvStr = ''; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0);//從服務(wù)器端接受返回信息 if (bytes <= 0) return; recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes); if(recvStr!='') { richTextBox1.Text += '有數(shù)據(jù),!\r\n'; richTextBox1.ScrollToCaret(); } else { } Thread.Sleep(100); |
|