AI智能
改变未来

基于C# Winform实现简单的Socket服务端

连接机制:

代码:

[code]/** 服务端与客户端不同,客户端只需要开启一个新线程用于接收服务端发来的消息即可* 而对于服务端,需要开启两个线程,一个线程用于时刻监听连接进来的客户端,一个用来接收客户端发来的消息*/using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.Threading;namespace SocketServer{public partial class Form1 : Form{/// <summary>/// socket套接字/// </summary>Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);/// <summary>/// 客户端/// </summary>Socket socketClienCon = null;/// <summary>/// 客户端信息/// </summary>string clientIpMsg = string.Empty;/// <summary>/// 服务器是否关闭  false:未关闭  true:已关闭/// </summary>bool isClose = false;public Form1(){InitializeComponent();}private void btnOpen_Click(object sender, EventArgs e){try{IPAddress ip = IPAddress.Parse(this.txtIp.Text.ToString().Trim());  //服务端IP地址int port = int.Parse(this.txtPort.Text.ToString().Trim());  //服务端端口号IPEndPoint ipe = new IPEndPoint(ip, port);  //网络终结点socketServer.Bind(ipe);  //绑定网络终结点socketServer.Listen(10);  //开始监听客户端连接(10:最大连接数量10)isClose = false;this.lstRev.Items.Add(string.Format(\"服务器已开启,开始监听消息\"));Thread clientThread = new Thread(ListenTh);  //创建一个线程,用于监听客户端连接clientThread.IsBackground = true;  //设置为后台线程clientThread.Start();  //开启线程Thread revThread = new Thread(RevTh);  //创建一个线程,用于监听客户端发来的消息revThread.IsBackground = true;//设置为后台线程revThread.Start();  //开启线程}catch (Exception ex){string errorMsg = string.Format(\"服务器开启失败,失败原因:{0}\", ex.Message.ToString());this.lstRev.Items.Add(errorMsg);}}/// <summary>/// 监听客户端/// </summary>private void ListenTh(){while (!isClose){try{socketClienCon = socketServer.Accept();  //为监听到的客户端创建新的套接字IPAddress clientIp = (socketClienCon.RemoteEndPoint as IPEndPoint).Address;  //获取连接的客户端的IP地址int clientPort = (socketClienCon.RemoteEndPoint as IPEndPoint).Port;  //获取连接的客户端的端口号clientIpMsg = string.Format(\"客户端IP:{0},端口号:{1}\", clientIp, clientPort);OnlineClient(clientIpMsg);  //在线用户并打印到在线用户窗口}catch (Exception ex){string error = string.Format(\"监听客户端信息异常,错误原因:{0}\", ex.Message.ToString());Recevice(error);break;}}}delegate void OnlineClientDele(string clientMsg);  //创建在线用户委托方法/// <summary>/// 在线用户/// </summary>/// <param name=\"clientMsg\">在线用户信息</param>private void OnlineClient(string clientMsg){if (this.InvokeRequired){OnlineClientDele oel = new OnlineClientDele(OnlineClient);this.Invoke(oel, new object[] { clientMsg });}else{this.lstClient.TopIndex = this.lstClient.Items.Count - 1;this.lstClient.Items.Add(clientMsg);}}/// <summary>/// 接收客户端消息/// </summary>private void RevTh(){while (!isClose){if(socketClienCon!=null){try{byte[] clientMsg = new byte[1024];  //创建接收消息缓存数组int msgLen = socketClienCon.Receive(clientMsg);  //接收从客户端发来的数据if (msgLen == 0){break;}else{string msg = string.Format(\"【收到 ← 来自:{0}】:{1}\", clientIpMsg, Encoding.ASCII.GetString(clientMsg, 0, msgLen));Recevice(msg);  //接收消息并打印到对话窗口}}catch (Exception ex){string error = string.Format(\"接收客户端消息异常,错误原因:{0}\", ex.Message.ToString());Recevice(error);break;}}}}delegate void ReceviceDele(string msgStr); //创建接收消息委托方法/// <summary>/// 接收消息/// </summary>/// <param name=\"msg\">客户端发来的消息</param>private void Recevice(string msg){if (this.InvokeRequired){ReceviceDele rel = new ReceviceDele(Recevice);this.Invoke(rel, new object[] { msg });}else{this.lstRev.TopIndex = this.lstRev.Items.Count - 1;this.lstRev.Items.Add(msg);}}/// <summary>/// 发送消息/// </summary>/// <param name=\"sender\"></param>/// <param name=\"e\"></param>private void btnSend_Click(object sender, EventArgs e){string msg = this.txtSend.Text.ToString().Trim();byte[] msgByt = Encoding.ASCII.GetBytes(msg);socketClienCon.Send(msgByt);this.lstRev.Items.Add(string.Format(\"【发送 → 至 {0}】:{1}\",clientIpMsg, msg));}private void Form1_FormClosing(object sender, FormClosingEventArgs e){isClose = true;socketServer.Close();}private void btnClose_Click(object sender, EventArgs e){isClose = true;socketServer.Close();}}}

本文为作者自行手写测试代码,如有雷同,万分荣幸,感谢在留言区指出错误和不同的观点,谢谢!

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 基于C# Winform实现简单的Socket服务端