解析从服务器收到的消息

本文关键字:消息 服务器 | 更新日期: 2023-09-27 18:31:04

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

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

但真正发生的事情是,当我进入聊天室时,会出现一条带有">>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;
}

解析从服务器收到的消息

conn.server.BeginReceive(dat, 0, 1024, SocketFlags.None, new AsyncCallback(recibiendoF), so);
if (//Something has been received)
                {
                    mensajenuevo = msjerecibidoF(dat);
                }

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

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

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