本文讲述了C#简单的tcpserver!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:
实现一个简单的TCPserver,用tcplistener实现。
当收到客户端特定信息"101"时,发送给客户端"202“指令。
using System; using System.Text; using System.Net.Sockets; using System.Threading; using System.Net; namespace TCPServerTutorial { class Server { private TcpListener tcpListener; private Thread listenThread; public Server() { this.tcpListener = new TcpListener(IPAddress.Any, 3000); this.listenThread = new Thread(new ThreadStart(ListenForClients)); this.listenThread.Start(); Console.WriteLine("Server started at {0} :{1} @ {2}", IPAddress.Any, 1031, DateTime.Now.ToString()); } private void ListenForClients() { this.tcpListener.Start(); while (true) { //blocks until a client has connected to the server TcpClient client = this.tcpListener.AcceptTcpClient(); //create a thread to handle communication //with connected client Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(client); } } private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; Console.WriteLine("Client @[{0}] connected @{1}", tcpClient.Client.LocalEndPoint,DateTime.Now.ToString()); NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead=0; //bool isRight=false; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { //a socket error has occured Console.WriteLine("Error:receive msg error"); break; } if (bytesRead == 0) { //the client has disconnected from the server Console.WriteLine("Client @[{0}] disconnect @{1}", tcpClient.Client.LocalEndPoint,DateTime.Now.ToString()); break; } //message has successfully been received ASCIIEncoding encoder = new ASCIIEncoding(); //System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); string recvstr=encoder.GetString(message, 0, bytesRead); Console.WriteLine("Recv:[{1}]:msg:@[{0}] @{2}", recvstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString()); //send msg to client string sendstr = "Server OK"; if (recvstr=="101") { //isRight = true; sendstr = "202"; Console.ForegroundColor = ConsoleColor.Red; } else { Console.ForegroundColor = ConsoleColor.White; } byte[] buffer = encoder.GetBytes(sendstr); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); Console.WriteLine("Sent:[{1}]:msg:@[{0}] @{2} ", sendstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString()); } tcpClient.Close(); } } }
更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。
想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!