UI界面:
实现:
服务端Server :开启服务端按钮点击事件
Thread threadWatch = null; //负责监听客户端的线程Socket socketWatch = null; //负责监听客户端的套接字private void button3_Click(object sender, EventArgs e){try{//定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//服务端发送信息 需要1个IP地址和端口号IPAddress ipaddress = IPAddress.Parse(this.txtIPServer.Text.Trim()); //获取文本框输入的IP地址//将IP地址和端口号绑定到网络节点endpoint上IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(this.txtPortServer.Text.Trim())); //获取文本框上输入的端口号//监听绑定的网络节点 socketWatch.Bind(endpoint);//将套接字的监听队列长度限制为20socketWatch.Listen(20);//创建一个监听线程threadWatch = new Thread(WatchConnecting);//将窗体线程设置为与后台同步threadWatch.IsBackground = true;//启动线程 threadWatch.Start();//启动线程后 txtMsg文本框显示相应提示txtMsgServer.AppendText("开始监听客户端传来的信息!" + "\r\n");this.button3.Enabled = false;}catch (Exception ex){txtMsgServer.AppendText("服务端启动服务失败!" + "\r\n");this.button3.Enabled = true;} }//创建一个负责和客户端通信的套接字Socket socConnection = null;/// <summary>/// 监听客户端发来的请求/// </summary>private void WatchConnecting(){while (true) //持续不断监听客户端发来的请求 {socConnection = socketWatch.Accept();txtMsgServer.AppendText("客户端连接成功! " + "\r\n");//创建一个通信线程ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);Thread thr = new Thread(pts);thr.IsBackground = true;//启动线程 thr.Start(socConnection);}}/// <summary>/// 接收客户端发来的信息/// </summary>/// <param name="socketClientPara">客户端套接字对象</param>private void ServerRecMsg(object socketClientPara){Socket socketServer = socketClientPara as Socket;while (true){//创建一个内存缓冲区 其大小为1024*1024字节 即1Mbyte[] arrServerRecMsg = new byte[1024 * 1024];try{//将接收到的信息存入到内存缓冲区,并返回其字节数组的长度int length = socketServer.Receive(arrServerRecMsg);//将机器接受到的字节数组转换为人可以读懂的字符串string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);//将发送的字符串信息附加到文本框txtMsg上txtMsgServer.AppendText("客户端 " + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n");}catch (Exception ex){txtMsgServer.AppendText("客户端已断开连接!" + "\r\n");break;}}}/// <summary>/// 获取当前系统时间的方法/// </summary>/// <returns>当前时间</returns>private DateTime GetCurrentTime(){DateTime currentTime = new DateTime();currentTime = DateTime.Now;return currentTime;}
服务端发送消息按钮点击事件:
private void button1_Click(object sender, EventArgs e){//调用 ServerSendMsg方法 发送信息到客户端ServerSendMsg(this.txtSendMsgServer.Text.Trim());this.txtSendMsgServer.Clear();}/// <summary>/// 发送信息到客户端的方法/// </summary>/// <param name="sendMsg">发送的字符串信息</param>private void ServerSendMsg(string sendMsg){try{//将输入的字符串转换成 机器可以识别的字节数组byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendMsg);//向客户端发送字节数组信息 socConnection.Send(arrSendMsg);//将发送的字符串信息附加到文本框txtMsg上txtMsgServer.AppendText("服务器 " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n");}catch (Exception ex){txtMsgServer.AppendText("客户端已断开连接,无法发送信息!" + "\r\n");}}
客户端Client :开启客户端按钮点击事件
//创建 1个客户端套接字 和1个负责监听服务端请求的线程Socket socketClient = null;Thread threadClient = null;private void button4_Click(object sender, EventArgs e){//定义一个套字节监听 包含3个参数(IP4寻址协议,流式连接,TCP协议)socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//需要获取文本框中的IP地址IPAddress ipaddress = IPAddress.Parse(this.txtIPClient.Text.Trim());//将获取的ip地址和端口号绑定到网络节点endpoint上IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(this.txtPortClient.Text.Trim()));//这里客户端套接字连接到网络节点(服务端)用的方法是Connect 而不是Bindtry{socketClient.Connect(endpoint);this.txtMsgClient.AppendText("客户端连接服务端成功!" + "\r\n");this.button4.Enabled = false;//创建一个线程 用于监听服务端发来的消息threadClient = new Thread(RecMsg);//将窗体线程设置为与后台同步threadClient.IsBackground = true;//启动线程 threadClient.Start();}catch (Exception ex){this.txtMsgClient.AppendText("远程服务端断开,连接失败!" + "\r\n");} }/// <summary>/// 接收服务端发来信息的方法/// </summary>private void RecMsg(){while (true) //持续监听服务端发来的消息 {try{//定义一个1M的内存缓冲区 用于临时性存储接收到的信息byte[] arrRecMsg = new byte[1024 * 1024];//将客户端套接字接收到的数据存入内存缓冲区, 并获取其长度int length = socketClient.Receive(arrRecMsg);//将套接字获取到的字节数组转换为人可以看懂的字符串string strRecMsg = Encoding.UTF8.GetString(arrRecMsg, 0, length);//将发送的信息追加到聊天内容文本框中txtMsgClient.AppendText("服务端 " + GetCurrentTime() + "\r\n" + strRecMsg + "\r\n");}catch (Exception ex){this.txtMsgClient.AppendText("远程服务器已中断连接!" + "\r\n");this.button4.Enabled = true;break;}}}
断开按钮点击事件:
/// <summary>/// 断开客户端/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button5_Click(object sender, EventArgs e){socketClient.Close();this.txtMsgClient.AppendText("已关闭连接" + "\r\n");}
客户端发送消息按钮点击事件:
private void button2_Click(object sender, EventArgs e){//调用ClientSendMsg方法 将文本框中输入的信息发送给服务端ClientSendMsg(this.txtSendMsgClient.Text.Trim());this.txtSendMsgClient.Clear(); }/// <summary>/// 发送字符串信息到服务端的方法/// </summary>/// <param name="sendMsg">发送的字符串信息</param>private void ClientSendMsg(string sendMsg){try{//将输入的内容字符串转换为机器可以识别的字节数组byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);//调用客户端套接字发送字节数组 socketClient.Send(arrClientSendMsg );//将发送的信息追加到聊天内容文本框中txtMsgClient.AppendText("客户端 " + GetCurrentTime() + "\r\n" + buffer + "\r\n");}catch (Exception ex){this.txtMsgClient.AppendText("远程服务器已中断连接,无法发送消息!" + "\r\n");}}
-------------------------------------------------------------------------------------------自此---------------------------------------------------------------------------------------------------
以上是完成socket通信winfrom程序的全部内容
其中socket连接方式有长连接和短连接,并未体现出来