socket.beginsendto和socket.beginreceivefrom未发送或接收数据

发布于 2025-02-12 10:26:23 字数 4410 浏览 0 评论 0原文

我正在尝试使用UDP插座为新游戏制作专用服务器。我正在使用socket.beginsendto()socket.beginreceivefrom()方法以发送我的数据。

我正在从这两种方法中收到回调,但是当我尝试encoding.ascii.getString(buffer)时,它没有向我显示任何字符串。我不确定发送时是否有问题,或者在收到时是否存在问题。

我知道UDP不能保证传输,这就是为什么我尝试将数据发送到两次大约10次的原因。每次,我都会收到一个回调,该回调是在客户端发送数据并在服务器端接收到数据。但是,正如我所说,当我尝试使用编码读取数据时,它一无所获。接收数据时,我尝试进行字符串空或空检查。它说字符串不是空的,但是当我尝试console.writeline()时,它在控制台中什么也没有显示。

这是我将数据发送到服务器的客户端代码:

public void SendMessage(Activity activityCode, String inputedString) //I am changed this
{
    byte[] data = readMessage.WriteData(activityCode, inputedString);
    if(data != null)
    {
        Debug.Log(data.Length); //this returned 11
        clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
    }
    
    Array.Clear(readMessage.data, 0, readMessage.data.Length);
}

private void OnSend(IAsyncResult ar)
{
    Debug.Log("sent"); //I am getting this callback in my console
}

这是我的服务器代码,我正在接收数据:

private void StartReceiveingData()
{
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        //The epSender identifies the incoming clients
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    StaticTest.printDData();
    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint epSender = (EndPoint)ipeSender;
    serverSocket.EndReceiveFrom(ar, ref epSender);
    
    StartReceiveingData();
}

这是我正在读取数据的地方:

static public class StaticTest
{
    static public byte[] byteData = new byte[1024];
    
    public static void printDData()
    {
        Console.WriteLine("Reding the received data" + Encoding.UTF8.GetString(byteData));
    }
}

“


:我尝试了此代码,但它仍然不起作用

private void StartReceiveingData()
{     
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        //The epSender identifies the incoming clients
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint epSender = (EndPoint)ipeSender;
    int numData = serverSocket.EndReceiveFrom(ar, ref epSender);
        
    if (!clientList.ContainsKey(epSender))
    {
        Client client = new Client(epSender);
        clientList.Add(epSender, client);     
    }
    if(clientList.TryGetValue(epSender, out Client client1))
    {
        string _receivedData = Encoding.UTF8.GetString(byteData, 0, numData);
        Console.WriteLine(_receivedData + " Data that came");
        //client1.RecieveDataFromMyGameObject(_receivedData);
    }

    StartReceiveingData();
}

:是我正在阅读数据的地方:

public string TakeActions(string _recivedData)
{
    int activityInput = Convert.ToInt32(_recivedData.Substring(0,1)); //there is an error
    ActivityRequest activity = (ActivityRequest)activityInput;
    Console.WriteLine("Current activity Number : " + activity);

    if(activity == ActivityRequest.SetupClient)
    {
        SetupClientDataActivity.setupClientData(client,_recivedData.Substring(1,_recivedData.Length-1));
    }
    else if(activity == ActivityRequest.MatchMaking)
    {
        Console.WriteLine("Asking Room manager to get into a room");
        // roomManager.AddAClientToARoom(client); 
    }

    return null;
}

I am trying to make a dedicated server for my new game using UDP sockets. I am using Socket.BeginSendTo() and Socket.BeginReceiveFrom() methods in order to send my data.

I am receiving the callbacks from both the methods, but when I am trying to Encoding.ASCII.GetString(buffer) it is not showing me any strings. I am not sure if there is a problem while sending, or if there is a problem while receiving.

I know that UDP does not guarantee the transmission, that's why I tried to send my data more then twice more like 10 times. Each time, I receive a callback that the data is sent on the client side and the data is received on the server side. But, as I said, when I am trying to read the data using Encoding, it shows nothing. I tried to do a string null or empty check while receiving the data. It said that the string is not empty, but when I try to Console.WriteLine(), it showed nothing in the console.

Here is the client code, where I am sending the data to the server:

public void SendMessage(Activity activityCode, String inputedString) //I am changed this
{
    byte[] data = readMessage.WriteData(activityCode, inputedString);
    if(data != null)
    {
        Debug.Log(data.Length); //this returned 11
        clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
    }
    
    Array.Clear(readMessage.data, 0, readMessage.data.Length);
}

private void OnSend(IAsyncResult ar)
{
    Debug.Log("sent"); //I am getting this callback in my console
}

Here is my server code, where I am receiving the data:

private void StartReceiveingData()
{
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        //The epSender identifies the incoming clients
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    StaticTest.printDData();
    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint epSender = (EndPoint)ipeSender;
    serverSocket.EndReceiveFrom(ar, ref epSender);
    
    StartReceiveingData();
}

And here is where I am reading the data:

static public class StaticTest
{
    static public byte[] byteData = new byte[1024];
    
    public static void printDData()
    {
        Console.WriteLine("Reding the received data" + Encoding.UTF8.GetString(byteData));
    }
}

image


UPDATE: I tried this code, but it still does not work:

private void StartReceiveingData()
{     
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        //The epSender identifies the incoming clients
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint epSender = (EndPoint)ipeSender;
    int numData = serverSocket.EndReceiveFrom(ar, ref epSender);
        
    if (!clientList.ContainsKey(epSender))
    {
        Client client = new Client(epSender);
        clientList.Add(epSender, client);     
    }
    if(clientList.TryGetValue(epSender, out Client client1))
    {
        string _receivedData = Encoding.UTF8.GetString(byteData, 0, numData);
        Console.WriteLine(_receivedData + " Data that came");
        //client1.RecieveDataFromMyGameObject(_receivedData);
    }

    StartReceiveingData();
}

And here is where I am reading the data:

public string TakeActions(string _recivedData)
{
    int activityInput = Convert.ToInt32(_recivedData.Substring(0,1)); //there is an error
    ActivityRequest activity = (ActivityRequest)activityInput;
    Console.WriteLine("Current activity Number : " + activity);

    if(activity == ActivityRequest.SetupClient)
    {
        SetupClientDataActivity.setupClientData(client,_recivedData.Substring(1,_recivedData.Length-1));
    }
    else if(activity == ActivityRequest.MatchMaking)
    {
        Console.WriteLine("Asking Room manager to get into a room");
        // roomManager.AddAClientToARoom(client); 
    }

    return null;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回忆凄美了谁 2025-02-19 10:26:23

您的OnSend回调需要调用socket.endsendto()以完成发送操作,并告诉您操作是否成功。

您的onReceive回调是调用socket.endreceivefrom(),但是您忽略了结果,您正在尝试在调用<之前打印bytedata代码> endReceiveFrom()要完成读取操作,并告诉您实际写了多少个字节bytedata

而是尝试一下:

public void SendMessage(Activity activityCode, String inputedString)
{
    byte[] data = readMessage.WriteData(activityCode, inputedString);
    if (data != null)
    {
        Debug.Log($"sending {data.Length} bytes");

        try
        {
            clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
    
    Array.Clear(readMessage.data, 0, readMessage.data.Length);
}

private void OnSend(IAsyncResult ar)
{
    try
    {
        int numBytes = clientSocket.EndSendTo(ar);
        Debug.Log($"sent {numBytes} bytes");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
private void StartReceiveingData()
{
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    try
    {
        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint epSender = (EndPoint)ipeSender;
        int numBytes = serverSocket.EndReceiveFrom(ar, ref epSender);
    
        StaticTest.printDData(numBytes);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

    StartReceiveingData();
}
static public class StaticTest
{
    static public byte[] byteData = new byte[1024];
    
    public static void printDData(int numBytes)
    {
        Console.WriteLine("Received data: {0}", Encoding.UTF8.GetString(byteData, 0, numBytes));
    }
}

Your OnSend callback needs to call Socket.EndSendTo() to finish the send operation and tell you whether the operation was successful or not.

Your OnReceive callback is calling Socket.EndReceiveFrom(), but you are ignoring its result, and you are trying to print the byteData before calling EndReceiveFrom() to finish the read operation and tell you how many bytes were actually written into byteData.

Try this instead:

public void SendMessage(Activity activityCode, String inputedString)
{
    byte[] data = readMessage.WriteData(activityCode, inputedString);
    if (data != null)
    {
        Debug.Log(
quot;sending {data.Length} bytes");

        try
        {
            clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
    
    Array.Clear(readMessage.data, 0, readMessage.data.Length);
}

private void OnSend(IAsyncResult ar)
{
    try
    {
        int numBytes = clientSocket.EndSendTo(ar);
        Debug.Log(
quot;sent {numBytes} bytes");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
private void StartReceiveingData()
{
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    try
    {
        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint epSender = (EndPoint)ipeSender;
        int numBytes = serverSocket.EndReceiveFrom(ar, ref epSender);
    
        StaticTest.printDData(numBytes);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

    StartReceiveingData();
}
static public class StaticTest
{
    static public byte[] byteData = new byte[1024];
    
    public static void printDData(int numBytes)
    {
        Console.WriteLine("Received data: {0}", Encoding.UTF8.GetString(byteData, 0, numBytes));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文