我是靠谱客的博主 追寻流沙,这篇文章主要介绍c#中tcp协议服务器同时接收客户端的数据,现在分享给大家,希望可以做个参考。


//服务器为每一个连接客户端产生一个线程,这样接受多个连接:
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();
}

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;
    NetworkStream clientStream = tcpClient.GetStream();

    byte[] message = new byte[4096];
    int bytesRead;

    while (true)
    {
        bytesRead = 0;
        try
        {
            //blocks until a client sends a message
            bytesRead = clientStream.Read(message, 0, 4096);
        }
        catch
        {
            //a socket error has occured
            break;
        }

        if (bytesRead == 0)
        {
            //the client has disconnected from the server
            break;
        }

        //message has successfully been received
        ASCIIEncoding encoder = new ASCIIEncoding();
        System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
    }
    tcpClient.Close();
}

最后

以上就是追寻流沙最近收集整理的关于c#中tcp协议服务器同时接收客户端的数据的全部内容,更多相关c#中tcp协议服务器同时接收客户端内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(119)

评论列表共有 0 条评论

立即
投稿
返回
顶部