zoukankan      html  css  js  c++  java
  • 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();
            }
    
    
        }
    
    
    }
  • 相关阅读:
    PHP 处理历史数据的伪代码
    PHP 算法之 -- 计算器设计
    PHP
    PHP-设计模式之-中介者模式
    删除更新数据库字段
    MySQL update 链表 (一个表数据当做条件错误时候的转换)
    题解 CF506C Mr. Kitayuta vs. Bamboos
    题解 LOJ2049 「HNOI2016」网络
    题解 CF1349C Orac and Game of Life
    题解 CF1349B Orac and Medians
  • 原文地址:https://www.cnblogs.com/qiri07/p/4321902.html
Copyright © 2011-2022 走看看