[C#]使用TcpListener及TcpClient开发一个简单的Chat工具

本例子比较简单,使用的是控制台程序开发,若需要使用该软件作为演示,必须先运行服务端,再运行客户端。

因为是首次接触该方面的知识,写得比较简陋,如有更好的建议,请提出,谢谢!

一、编写服务器端代码,如下:

using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace ChatServer { class Program { static void Main(string[] args) { bool cancel = false; byte[] buffer = new byte[1024]; string message; byte[] messageBytes; int count = 0; TcpListener tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, 13000)); tcpListener.Start(); Console.WriteLine("Waiting for a connection... "); TcpClient tcpClient = tcpListener.AcceptTcpClient(); Console.WriteLine("Connected."); NetworkStream stream = tcpClient.GetStream(); Task.Factory.StartNew(() => { while ((count = stream.Read(buffer, 0, buffer.Length)) != 0) { Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Reply from server {tcpClient.Client.LocalEndPoint.ToString()}:{Encoding.UTF8.GetString(buffer, 0, count)}"); } }); Task t = Task.Factory.StartNew(() => { while(!cancel) { message = Console.ReadLine(); if (message.ToUpper() == "Y") { cancel = true; return; } messageBytes = Encoding.UTF8.GetBytes(message); stream.Write(messageBytes, 0, messageBytes.Length); } }); if (cancel) tcpClient.Close(); while (true) { if (t != null && t.IsCompleted) break; } } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wspgzz.html