从客户端一次接收数据并显示在消息框中

时间:2019-04-30 21:48:29

标签: c# sockets tcp

我将数据从客户端发送到服务器,但是服务器接收到数据并间歇地显示它 必需:接收数据并将其汇总到一个字符串变量中以进行处理(例如,在消息框中显示) .. .. .... .. .... .. .... .. .... .. ..

    public void WaitForData(System.Net.Sockets.Socket soc)
    {
        try
        {
            if (pfnWorkerCallBack == null)
            {
                // Specify the call back function which is to be 
                // invoked when there is any write activity by the 
                // connected client
                pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
            }
            SocketPacket theSocPkt = new SocketPacket();
            theSocPkt.m_currentSocket = soc;
            // Start receiving any data written by the connected client
            // asynchronously
            soc.BeginReceive(theSocPkt.dataBuffer, 0,
                               theSocPkt.dataBuffer.Length,
                               SocketFlags.None,
                               pfnWorkerCallBack,
                               theSocPkt);
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }

    }
    // This the call back function which will be invoked when the socket
    // detects any client writing of data on the stream
    public void OnDataReceived(IAsyncResult asyn)
    {
        try
        {
            SocketPacket socketData = (SocketPacket)asyn.AsyncState;
            int iRx = 0;
            // Complete the BeginReceive() asynchronous call by EndReceive() method
            // which will return the number of characters written to the stream 
            // by the client
            iRx = socketData.m_currentSocket.EndReceive(asyn);
            char[] chars = new char[iRx + 1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(socketData.dataBuffer,
                                     0, iRx, chars, 0);
            System.String szData = new System.String(chars);
            richTextBoxReceivedMsg.Text = richTextBoxReceivedMsg.Text + szData;
            Sdata = szData;
            // Continue the waiting for data on the Socket
            WaitForData(socketData.m_currentSocket);
            //richTextBoxReceivedMsg.Text = richTextBoxReceivedMsg.Text + "\r\n";

        }
        catch (ObjectDisposedException)
        {
            System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }

0 个答案:

没有答案