Socket服务端接受多个客户端的连接(.NET)

 

  本文模拟一个判断数据是否大于100的服务器端接受多个客户端的连接,为多个客户端提供服务的演示,例子比较简单,只为模拟一种场景,起到为入门读者踏入网络编程的指引。

 

 服务器端:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Threading; using System.Net.Sockets; namespace Net.Dale.TcpServerTest { class Program { static void Main(string[] args) { try { //把IP字符串形式转换为IP实例形式 IPAddress ipa = IPAddress.Parse("127.0.0.1"); //监听端口8000 TcpListener mylsn = new TcpListener(ipa, 8000); //开启监听 mylsn.Start(); //输出监听成功的信息 Console.WriteLine("在8000端口启动服务,等待连接"); //等待处理接入连接请求 while (true) { Socket mysock = mylsn.AcceptSocket(); Console.WriteLine("有连接,连接来自" + mysock.RemoteEndPoint+" "+mysock.GetHashCode()); //构造新实例 DoWork dw = new DoWork(mysock,mylsn); Thread rcv = new Thread(new ThreadStart(dw.rcvMethod)); rcv.Start(); } } catch { } finally { } } } public class DoWork { public Socket mysock; public TcpListener mylsn; public DoWork(Socket s, TcpListener t) { mysock = s; mylsn = t; } public void rcvMethod() { while (true) { try { //接收客户端消息 byte[] data = new byte[100]; mysock.Receive(data); string rt = System.Text.UTF8Encoding.UTF8.GetString(data); Console.WriteLine(rt); if (int.Parse(rt) > 100) { //返回信息 mysock.Send(UTF8Encoding.UTF8.GetBytes("您输入的数据大于100")); } else { //返回信息 mysock.Send(UTF8Encoding.UTF8.GetBytes("您输入的数据小于100")); } } catch { Console.WriteLine(mysock.GetHashCode()); Console.WriteLine("一个客户端已经断开连接!"); mysock.Close(); break; } } } } }

 

注释:当服务端监听到有新客户端连接时,会单独创建一个线程为该客户端服务;

 

客户端:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace Net.Dale.TcpClientTest { class Program { static void Main(string[] args) { //新建客户端套接字 TcpClient tclient = new TcpClient(); //连接服务器 tclient.Connect("127.0.0.1", 8000); //得到流 Stream stm = tclient.GetStream(); Console.WriteLine("输入要发送的消息"); //构造新实例 DoWork dw=new DoWork(stm,tclient); Thread snd = new Thread(new ThreadStart(dw.sndMethod)); snd.Start(); snd.Join(); } } } public class DoWork { public Stream stm; public TcpClient tclient; public DoWork(Stream s, TcpClient t) { stm = s; tclient = t; } public void sndMethod() { while (true) { try { //读入要传输的字符 string msg = Console.ReadLine(); int error = int.Parse(msg); if (msg == "exit" || msg == "EXIT") { Console.WriteLine("客户端成功退出!"); break; } //发送字符串 byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(msg); stm.Write(data, 0, data.Length); //接受服务器返回的消息 byte[] back = new byte[1024]; int k = stm.Read(back, 0, 1024); //输出服务器返回的消息 Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(back)); } catch (Exception err) { Console.WriteLine(err.Message+"/n程序退出!"); break; } } } }

你可能感兴趣的:(Socket服务端接受多个客户端的连接(.NET))