【问题标题】:Parse the received message from the server解析从服务器接收到的消息
【发布时间】:2015-01-17 02:13:28
【问题描述】:

我遇到的问题是将我通过服务器读取的字节解析到客户端接口并向他们显示收到的消息。

一般的想法是发送一条消息,消息到达服务器,然后将消息发送回连接到聊天室的所有客户端。

但真正发生的是,当我进入聊天室时,会出现一条带有“>>IgnUsername”的消息,以标记新用户已进入聊天室。

当我尝试发送诸如“Hello”之类的消息时,服务器会正​​确接收消息,但是当需要将消息发送回用户时,屏幕上显示的却是“>>IgnUsername”。这是原始消息。 我什至不确定这是实际解决我遇到的问题的唯一错误代码提取。

conn.server.BeginReceive(dat, 0, 1024, SocketFlags.None, new AsyncCallback(recibiendoF), so);

if (//Something has been received)
{
    mensajenuevo = msjerecibidoF(dat);
}

这是回调

public void recibiendoF(IAsyncResult ar)
{
    try
    {
        StateObject so = (StateObject)ar.AsyncState;
        conn.server = so.workSocket;

        int bytesRead = conn.server.EndReceive(ar);

        if (bytesRead > 0)
        {
            string mensajote = System.Text.Encoding.ASCII.GetString(mensajenuevo);
            if (textBox_curMsg.InvokeRequired == true)
            {
                this.textBox_curMsg.BeginInvoke((MethodInvoker)delegate
                {
                    textBox_curMsg.Text = mensajote;
                });
            }
            else
                textBox_curMsg.Text = mensajote;
            //recibemsje();
        }
        else
        {
            if (so.sb.Length > 1)
            {
                string response = so.sb.ToString();
            }
            //recibemsje();
        }
    }
    catch
    {
    }
}

这是我在使用回调之前想使用的函数

public byte[] msjerecibidoF(byte[] msej)
{
    byte[] mensajeiro = new byte[1024];
    mensajeiro = msej;
    mensajenuevo = msej;
    return mensajeiro;
}

【问题讨论】:

  • 您将需要显示更多的代码,这些代码不会显示发送回的位置/方式/内容或任何其他内容。请阅读有关MCV 的常见问题解答。
  • 我在回调之前添加了回调和要使用的函数。问题是我真的无法选择我遇到问题的位。我会尽量让它紧凑。

标签: c# server


【解决方案1】:
conn.server.BeginReceive(dat, 0, 1024, SocketFlags.None, new AsyncCallback(recibiendoF), so);

if (//Something has been received)

                {
                    mensajenuevo = msjerecibidoF(dat);
                }

这不是它的工作方式。您正在使用立即返回的异步接收方法。回调是在实际接收发生时调用的。您的方法 msjerecibidoF(dat); 将传递一个空的 dat 或旧数据。

另外,在public void recibiendoF(IAsyncResult ar) 结束时,您必须再次致电onn.server.BeginReceive 才能接收下一条消息。

因为你已经发布了部分代码,这是我能回答的最好的。修复这些,然后看看...

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2012-09-01
    • 2022-01-19
    • 2018-03-30
    相关资源
    最近更新 更多