简体   繁体   English

问题 C# 中的套接字 TCP IP 在停止前只收到来自客户端的一条消息

[英]Problem socket TCP IP in C# received only one message from client before stop

I've a problem with my server in tcp/ip, because after received one message doesn't work.我的服务器在 tcp/ip 中出现问题,因为收到一条消息后不起作用。 I don't know if use a while true, and how to put it.我不知道使用 while 是否正确,以及如何放置。 Any suggestion?有什么建议吗?

Thank you谢谢

   my method()

        sdk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sdk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8052));
        sdk.Listen(10);
        Socket accepted = sdk.Accept();
        Buffer = new byte[accepted.SendBufferSize];
        int bytesRead = accepted.Receive(Buffer);
        byte[] formatted = new byte[bytesRead];
        for (int i = 0; i < bytesRead; i++)
        {
            formatted[i] = Buffer[i];
        }
        Debug.Log("\t Server" + "\n");
        string stradata = Encoding.ASCII.GetString(formatted);
        Debug.Log("-->" + "" + stradata + "\n\n");
        testo = stradata;
        //sdk.Close();   tried to uncomment 
        //accepted.Close(); tried to uncomment

You need to read from the socket continually, until you have read all the data that you want您需要不断地从套接字中读取数据,直到读取了您想要的所有数据

    sdk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    sdk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8052));
    sdk.Listen(10);
    Socket accepted = sdk.Accept();
    Buffer = new byte[accepted.SendBufferSize];
    while (true)
    {
        // begin reading continually from the socket

        // Socket::Receive() will block until it gets some data
        // Exception handling required here for when client closes connection
        int bytesRead = accepted.Receive(Buffer);
        byte[] formatted = new byte[bytesRead];
        for (int i = 0; i < bytesRead; i++)
        {
            formatted[i] = Buffer[i];
        }
        Debug.Log("\t Server" + "\n");
        string stradata = Encoding.ASCII.GetString(formatted);
        Debug.Log("-->" + "" + stradata + "\n\n");

        // Need to add some exit logic here eg,
        if(stradata.Contains("EXIT"))
            break;
    }
    sdk.Close(); 
    accepted.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM