c# - C# 网络中的同步

标签 c# tcp tcpclient tcpserver

我有这个简单的 tcp 服务器类

 class Server
{
    private TcpListener tcpListener;
    private Thread listenThread;

    public Server()
    {
        this.tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 3000);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
        Console.WriteLine("Hello");
    }


    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));
            Console.WriteLine("New connexion");
            clientThread.Start(client);
        }
    }

    private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        Console.WriteLine("Got Stream");

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

        Console.WriteLine("Initializing..");
        while (true)
        {
            bytesRead = 0;

            try
            {
                //blocks until a client sends a message
                Console.WriteLine("Reading..");
                bytesRead = clientStream.Read(message, 0, 4096);
                Console.WriteLine("Received something");
            }
            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();
            Console.WriteLine(encoder.GetString(message, 0, bytesRead));

        }

        tcpClient.Close();
    }

}

我只是在主函数中调用它,如下所示:

Server server = new Server();

在一个单独的客户端程序中,我有这个类

class TheClient
{
  public void ConnectV2()
    {


        TcpClient client = new TcpClient();

        IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);

        client.Connect(serverEndPoint);

        NetworkStream clientStream = client.GetStream();

        ASCIIEncoding encoder = new ASCIIEncoding();

        for (int i = 0; i < 20; i++)
        {

            byte[] buffer = encoder.GetBytes("Hello Server! " + i.ToString() + " ");

            Console.WriteLine("Processing..");

            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();
            Console.WriteLine("Hello Server sent");
        }


    }

}

我在主函数中调用它,例如

TheClient tc = new TheClient();

tc.ConnectV2();

我的问题是服务器程序似乎比客户端慢,他在来自客户端的第 13 条或更多消息之前没有使用react:

[由于声誉问题,我无法发布图片]

它会一次性读取前十几条消息,然后逐条读取其他消息。

如果我让服务器先发出消息,客户端就会收到消息,但它们都会停止,就像两者都等待对方发送某些内容一样。

有人可以向我解释一下这种行为吗?我如何控制和同步它?

最佳答案

TCP 不是基于消息的。它提供字节流。您有责任区分消息。另请注意,您可能在一次 Read 调用中仅收到消息的一部分。

这里有一个简单的方法:将消息作为单独的行发送。可能使用StreamWriter。使用StreamReader.ReadLine()接收消息。

这样您还可以使用更合理的编码,例如 Encoding.UTF8

除此之外,您的代码实际上很好并且可行。在 Stack Overflow 上看到几乎可以工作的 TCP 代码是极其罕见的。大多数代码都严重损坏。恭喜。

关于c# - C# 网络中的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552133/

相关文章:

c - C-Socket 管道损坏。如何只保持服务器运行?

php - Apache/PHP 进程在与 MySQL 交互时挂起

c++ - TCP Telnet 传输中丢失字符

java - 在 Java 中列出打开的 TCP 连接

C# 4.0 MemoryCache - 如何在对其依赖项进行更改时逐出依赖缓存条目

c# - 如何返回带有状态码的响应 JSON 数据?

c# - MOQ:如何将接口(interface)的模拟转换回接口(interface)

c# - 编码双字符指针返回值

c - 在c中使用TCP的服务器-客户端

c# - 判断一个TCP流是否已经断开