写了几个socket 通信的项目,现在整理下同步通信方式代码。环境是netcore3.1
服务端
第一步:
创建Socket 实例
IPAddress iPAddress = IPAddress.Parse(ip);
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
第二步:
绑定的IP 和端口
ServerSocket.Bind(new IPEndPoint(iPAddress, port));//绑定IP 地址,端口
第三步:
设置监听的客户端数量。
ServerSocket.Listen(10);
第四步:
启动一个线程任务,去监听客户端连接和发送消息。
Task.Factory.StartNew(ListenClinetConnect).Start();
下面是完整的代码
public class Server { private byte[] result = new byte[1024]; Socket ServerSocket; public bool Start(string ip,int port=8088) { try { IPAddress iPAddress = IPAddress.Parse(ip); ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ServerSocket.Bind(new IPEndPoint(iPAddress, port));//绑定IP 地址,端口 ServerSocket.Listen(10); Console.WriteLine("启动监听{0}成功",ServerSocket.LocalEndPoint.ToString()); //通过clientSocket 发送消息 Task.Factory.StartNew(ListenClinetConnect).Start(); //Thread thread = new Thread(ListenClinetConnect); Thread 方式 //thread.Start(); return true; } catch (Exception) { return false; } } private void ListenClinetConnect() { try { while (true) { Socket acceptSocket = ServerSocket.Accept(); acceptSocket.Send(Encoding.UTF8.GetBytes("Server Say Hello")); Task t = new Task(()=>ReceiveMessage(acceptSocket)); t.Start(); } } catch (Exception ex) { throw; } } private void ReceiveMessage(object acceptSocket) { Socket myClientSocket = (Socket)acceptSocket; while (true) { try { //通过clinetSocket 接收数据 int receiveNumber = myClientSocket.Receive(result); Console.WriteLine("接收到客户端{0}消息{1}",myClientSocket.RemoteEndPoint.ToString(),Encoding.UTF8.GetString(result,0,receiveNumber)); } catch (Exception ex) { Console.WriteLine(ex.Message); myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); break; } } } }
启动socket服务
static void Main(string[] args) { Console.WriteLine("Hello World!"); Server server = new Server(); server.Start("192.168.1.18"); Console.ReadLine(); }
客户端
第一步:
创建socket实例
IPAddress iPAdress = IPAddress.Parse(ip);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
第二步:
连接到socket,连接可以设置超时时间,有需要可以自行百度
clientSocket.Connect(new IPEndPoint(iPAdress, port));
第三步:
创建一个线程任务去接收消息。
Task task = new Task(ReceiveMsg);
task.Start();
下面是完整代码
public class Client { private byte[] result = new byte[1024]; private Socket clientSocket; public bool Start(string ip,int port=8088) { try { // 设定服务地址 IPAddress iPAdress = IPAddress.Parse(ip); clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(new IPEndPoint(iPAdress, port)); Console.WriteLine("连接服务器成功"); clientSocket.Send(Encoding.UTF8.GetBytes("连接成功了")); Task task = new Task(ReceiveMsg); task.Start(); return true; } catch (Exception) { Console.WriteLine("连接服务器失败"); return false; } } private void ReceiveMsg() { while (true) { if(clientSocket != null && clientSocket.Connected) { int receiveLenth = clientSocket.Receive(result); Console.WriteLine("接收到消息{0}", Encoding.UTF8.GetString(result, 0, receiveLenth)); } else { break; } } } public void SendMsg(string msg) { try { if(clientSocket!=null && clientSocket.Connected) { clientSocket.Send(Encoding.UTF8.GetBytes(msg)); }else { Console.WriteLine("无法连接到服务器"); } } catch (Exception ex) { throw; } } public void Close() { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); clientSocket.Dispose(); } }
连接到socket服务
static void Main(string[] args) { Console.WriteLine("Hello World!"); Client client = new Client(); client.Start("192.168.1.18"); string msg = ""; while (!msg.Equals("exit")) { Console.WriteLine("请输入消息"); msg = Console.ReadLine(); client.SendMsg(msg); } Console.WriteLine("您已退出!"); Console.ReadLine(); }
socket 同步小例子就写完了。
标签:同步,Console,socket,Start,例子,WriteLine,new,clientSocket,Socket From: https://www.cnblogs.com/htt4242/p/16905628.html