控件
打开链接
Socket socket;
// 打开连接
private void button1_Click(object sender, EventArgs e)
{button1.Enabled = false;button2.Enabled = true;//1 创建socket客户端对象socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);// 2 连接指定tcp服务器地址和端口号socket.Connect(new IPEndPoint(IPAddress.Parse("192.168.107.73"), 3000));// 3 开始接受连接 需要使用异步接受,一直处于接受状态StartReceive();
}
public void StartReceive()
{Task.Run(() =>{while (true){byte[] buffer = new byte[1024];// 自定义字节数组while (true){try{int length = socket.Receive(buffer);if (length == 0){// 如果客户端接受的数据长度为0,证明服务器断开了this.richTextBox1.Invoke((Action)(() =>{richTextBox1.AppendText("服务器已经断开");}));break;}else{ // 把接收到的数据转成字符串string value = Encoding.UTF8.GetString(buffer, 0, length);this.richTextBox1.Invoke((Action)(() =>{richTextBox1.AppendText("服务器发来消息:" + value + "\t\n");}));}}catch (Exception){// 证明客户关闭socket.Close();BeginInvoke(new Action(() =>{button1.Enabled = true;button2.Enabled = false;}));break;}}}});
}
断开连接
// 断开连接private void button2_Click(object sender, EventArgs e){button1.Enabled = true;button2.Enabled = false;socket.Shutdown(SocketShutdown.Both);// 关闭双向通信socket.Close();// 把客户端关闭}
发送信息
发送消息
private void button3_Click(object sender, EventArgs e)
{if (socket != null){byte[] bs = Encoding.UTF8.GetBytes("李克兢:"+this.textBox1.Text);socket.Send(bs);}
}