C#客户端socket多次发送接收

C# client socket multiple send and receive

我正在使用套接字进行 TCP-IP 连接,我想从客户端建立简单的系统发送-接收。

 Socket sck;
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("123.123.123.1"), 12345);
        try
        {
            sck.Connect(localEndpt);
        }
        catch
        {
            Console.Write("Unable to Connect");
        }
        while (true)
        {
            Console.WriteLine("Enter Text");
            string sendtext = Console.ReadLine();
            byte[] Data = Encoding.ASCII.GetBytes(sendtext);
            sck.Send(Data);
            Console.WriteLine("Data Sent!");

            byte[] bytesReceived = new byte[sck.ReceiveBufferSize];
            int bytes = 0;
            String strReceived = "";

            int dataAvailable = 0;
            while (dataAvailable == 0 || dataAvailable != sck.Available)
            {
                dataAvailable = sck.Available;
                Thread.Sleep(100); // if no new data after 100ms assume transmission finished
            }

            if (sck.Available > 0)
            {
                bytes = sck.Receive(bytesReceived, bytesReceived.Length, 0);
                strReceived+=Encoding.ASCII.GetString(bytesReceived, 0, bytes);
            }

            Console.WriteLine("Received from server: " + strReceived);
        }
        Console.Read();

问题是第一个请求通过但第二个请求没有通过,因为套接字不再可用(套接字"Availabe" 属性值为0)。我究竟做错了什么?建立多个发送-接收请求(按顺序)的最简单方法是什么?

Socket. Available NOT 表示套接字是否可用,但传入数据可读:
https://msdn.microsoft.com/en-us/library/ee425135.aspx

您的程序退出是因为它在发送消息后立即检查回复(传入数据)。在检查数据之前使用 Thread.Sleep

也许消息还没有发送出去,因为Socket.Send只是把它放到了网卡的输出缓冲区中。当套接字最终发送消息时,它将更新连接状态。如果它没有收到回复(在 TCP 连接上),它会在您查询状态时告诉您它已断开连接。在 UDP 上它什么也不会告诉你,因为 UDP 是无连接的。

这段代码对我来说没问题

    private List<Socket> _clients = new List<Socket>();
    private Thread _dataReceiveThread;
    private bool _isConnected;

    private void DataReceive()
    {
        while (_isConnected)
        {
            List<Socket> clients = new List<Socket>(_clients);
            foreach (Socket client in clients)
            {
                try
                {
                    if (!client.Connected) continue;
                    string txt = "";
                    while (client.Available > 0)
                    {
                        byte[] bytes = new byte[client.ReceiveBufferSize];
                        int byteRec = client.Receive(bytes);
                        if (byteRec > 0)
                            txt += Encoding.UTF8.GetString(bytes, 0, byteRec);
                    }
                    if (!string.IsNullOrEmpty(txt))
                        /* TODO: access the text received with "txt" */
                }
                catch (Exception e)
                {
                    Exception_Handler(e);
                }
            }
        }
    }

只需运行此代码即可开始

_isConnected = true;
_dataReceiveThread = new Thread(DataReceive);
_dataReceiveThread.Start();

更新Cross thread中的列表框:

这段代码可以放在评论区

myListBox1.Invoke((Action)(() => { myListBox1.Items.Add(txt) }));