C#TCP客户端发送但未接收消息

时间:2015-01-08 22:17:17

标签: c# sockets tcp websocket

我为TCP客户端继承了一些代码。它发送一条消息,然后在完成等待确认消息时。目前它发送消息,但是当它等待回复消息时它永远不会收到它。 SendMessage()方法就是所谓的外部方法。

我设置了断点并且可以看到它符合Receive()方法,但从来没有ReceiveCallback()

对正确方向的任何帮助或推动表示赞赏。

public class SocketService
{
    private ManualResetEvent connectDone = new ManualResetEvent(false);
    private ManualResetEvent sendDone = new ManualResetEvent(false);
    private ManualResetEvent receiveDone = new ManualResetEvent(false);

    string ipAddress;
    private int portNum;
    string returnMessage;
    // private string hostName = Dns.GetHostName ();

    public SocketService(string ipAddress, int portNum)
    {
        this.ipAddress = ipAddress;
        this.portNum = portNum;
    }

    public event Logging OnLogging;

    private void WriteLogMessage(string message)
    {
        if (this.OnLogging != null)
            this.OnLogging(message);
    }

    //char endOfLineSeparator = (char) 0x1C;
    //char cr = (char) 0x0D;
    //char vt = (char) 0x0B;

    public string SendMessage(string message)
    {
        IPAddress ip = IPAddress.Parse(this.ipAddress);
        IPEndPoint remoteEP = new IPEndPoint(ip, portNum);

        connectDone.Reset();

        Socket client = new Socket(AddressFamily.InterNetwork,
                                    SocketType.Stream,
                                    ProtocolType.Tcp);

        client.BeginConnect(remoteEP,
                            new AsyncCallback(ConnectCallback),
                            client);

        connectDone.WaitOne();

        //sendDone.Reset();

        WriteLogMessage("send message");

        Send(client, message);
        sendDone.WaitOne();

        //receiveDone.Reset();

        WriteLogMessage("receive message");

        Receive(client);
        receiveDone.WaitOne();

        client.Shutdown(SocketShutdown.Both);
        client.Close();

        return this.returnMessage;
    }

    private void Send(Socket client, String data)
    {
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        client.BeginSend(byteData,
                        0,
                        byteData.Length,
                        0,
                        new AsyncCallback(SendCallback),
                        client);
    }

    private void SendCallback(IAsyncResult ar)
    {
        Socket client = (Socket)ar.AsyncState;

        int bytesSent = client.EndSend(ar);

        sendDone.Set();
    }

    private void ConnectCallback(IAsyncResult ar)
    {
        Socket client = (Socket)ar.AsyncState;

        client.EndConnect(ar);

        connectDone.Set();
    }

    private void Receive(Socket client)
    {
        StateObject state = new StateObject(client);

        client.BeginReceive(state.Buffer,
                            0,
                            StateObject.BufferSize,
                            0,
                            new AsyncCallback(ReceiveCallback),
                            state);
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.WorkSocket;

        int bytesRead = client.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.StoredContent.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead));

            client.BeginReceive(state.Buffer,
                                0,
                                StateObject.BufferSize,
                                0,
                                new AsyncCallback(ReceiveCallback),
                                state);

            WriteLogMessage(state.StoredContent.ToString());
        }
        else
        {
            this.returnMessage = state.StoredContent.ToString();

            receiveDone.Set();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您的SendMessageReceive功能实际上并不适用。它们只发送和接收字节。他们没有“消息”的概念,在发送消息时不标记消息的结尾,也不在接收消息时识别消息的末尾。简而言之,您忘记实现网络协议,并假设TCP实际上是字节流服务时是一种消息服务。

如果您需要发送和接收消息,则必须精确定义“消息”是什么,并编写代码以发送和接收消息。它不会通过魔法发挥作用。

答案 1 :(得分:0)

正如David Schwartz指出的那样,你需要一种分隔信息的方法。

了解WebSocket data is framed

0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len |    Extended payload length    |
|I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
|N|V|V|V|       |S|             |   (if payload len==126/127)   |
| |1|2|3|       |K|             |                               |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
|     Extended payload length continued, if payload len == 127  |
+ - - - - - - - - - - - - - - - +-------------------------------+
|                               |Masking-key, if MASK set to 1  |
+-------------------------------+-------------------------------+
| Masking-key (continued)       |          Payload Data         |
+-------------------------------- - - - - - - - - - - - - - - - +
:                     Payload Data continued ...                :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
|                     Payload Data continued ...                |
+---------------------------------------------------------------+

答案 2 :(得分:0)

最后,这是一个无人知晓的事情。这些是HL7消息,并且消息末尾缺少隐藏的字符。接收方正在等待消息完成发送,但没有这个字符它从未看到完整的消息,因此从未发回确认。