C# TCP/IP (线程池监控)
服务端
private static TcpListener server; public static void Main1() { //定义接受的端口号 int port = 10010; //地址解析 IPAddress iPAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint ipPOrt = new IPEndPoint(iPAddress, port); //开启一个TcpListener用来监听端口 server = new TcpListener(ipPOrt); server.Start(); Console.Write("启动监听成功"); //线程池设置 ThreadPool.SetMaxThreads(2, 2); server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server); } private static void DoAcceptTcpclient(IAsyncResult result) { //获取监听事件,处理客户端请求 TcpListener listerer = (TcpListener)result.AsyncState; TcpClient client = listerer.EndAcceptTcpClient(result); List<TcpClient> clients = new List<TcpClient>(); clients.Add(client); Console.WriteLine("客户端建立完成,id{0}", client.Client.RemoteEndPoint.ToString()); //开一个线程,将处理客户端接受到的数据ParameterizedThreadStart和Start放的都是object //Thread thread = new Thread(new ParameterizedThreadStart(ReceiveMessageFromClient)); ////开启线程 //thread.Start(client); ThreadPool.QueueUserWorkItem(ReceiveMessageFromClient2, client); server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server); }private static void ReceiveMessageFromClient2(object reciveClient) { var threadID = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("当前运行的线程ID:" + threadID); //将reciveClient实体装换成TCPClient类 TcpClient client = reciveClient as TcpClient; if (client == null) { Console.WriteLine("client error"); return; } try { NetworkStream networkStream = client.GetStream();//获取网络数据流 BinaryReader reader = new BinaryReader(networkStream);//定义数据读取对象 BinaryWriter writer = new BinaryWriter(networkStream);//定义数据写入对象 while (true) { try { string strReader = reader.ReadString();//接收消息 // string[] strReaders = strReader.Split(new char[] { ' ' });//截取客服端信息 //Console.WriteLine("有客服端接入,客户IP:" + strReaders[0]);//输出接收客服端IP地址 string strWriter = "我是服务器,欢迎光临";//定义服务端要写的内容 Console.WriteLine("来自客服端的消息:" + strReader);//输出接收的消息 writer.Write(strWriter);//向对方发送消息 writer.Close(); // writer.Write(strReaders[1]);//向对方发送消息 } catch { Console.WriteLine("客户端关闭"); break; } } } catch { Console.WriteLine("接收数据失败"); } }
客户端
TcpClient tcpClient = new TcpClient();//创建一个TcpClient对象,自动分配主机IP地址和端口号 tcpClient.Connect("127.0.0.1", 10010);//连接服务器,其IP和端口号为127.0.0.1和888 if (tcpClient != null) { Console.WriteLine("连接服务器成功"); NetworkStream networkStream = tcpClient.GetStream();//获取网络数据流 BinaryReader reader = new BinaryReader(networkStream);//定义数据读取对象 BinaryWriter writer = new BinaryWriter(networkStream);//定义数据写入对象 string localip = "127.0.0.1";//存储本机IP,默认值为127.0.0.1 IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());//获取所有Ip地址 foreach (var item in ips) { //如果不是ipv6 if (!item.IsIPv6LinkLocal) { if (!item.IsIPv6Teredo) { localip = item.ToString(); } } } writer.Write(localip + " 你好服务器,我是客服端" + ass);//向服务器发送消息 while (true) { try { string strReader = reader.ReadString();//接收服务器发送的数据 if (strReader != null) { Console.WriteLine("来自服务器的消息:" + strReader + " " + ass);//输出接收服务器的消息 } } catch (Exception e) { tcpClient.Close(); Console.WriteLine("错误!!" + e.Message); break;//出错退出循环 } } } else { Console.WriteLine("连接服务器错误"); }
当某些情况需要客户端对接受数据的等待时间设置超时可以设置NetworkStream的ReadTimeout属性(单位为毫秒)
ps:参考网上博文,主要参考自https://blog.csdn.net/secret2316352792/article/details/99641915