UDP:客户端在服务器之前启动 [英] UDP: Client started before Server

查看:60
本文介绍了UDP:客户端在服务器之前启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚才在游戏中遇到了一些小故障,如果服务器在客户端之前启动,则一切正常,但是当客户端在服务器之前启动时,它们永远不会连接.这都是UDP

I have a bit of a glitch in my game just now, everything runs fine if the server is started before the client however when the client is started before the server they never connect. This is all UDP

问题发生在客户端尝试在服务器启动之前调用 recvfrom() 时,当发生这种情况时,客户端永远找不到服务器,服务器也永远找不到客户端.结果错误是一个 willblock.

The problem happens when the client tries to call recvfrom() before the server has started, when this happens the client never finds the server and the server never finds the client. The resulted error is a wouldblock.

如果我使用 recvfrom 停止客户端并在服务器之前启动客户端(客户端仍在发送数据,只是没有接收到数据),他们都会发现对方没问题.

If I stop the client using recvfrom and start the client before the server (the client is still sending data its just not receiving it) they both find each other no problem.

有什么办法可以解决这个问题?它现在看起来的方式是客户端无法在服务器不活动的情况下调用 recvfrom 或者它全部崩溃.是否可以进行检查以查看数据是否位于某个端口(服务器将发送的数据)?或者有没有更好的方法来做到这一点?

Whats the solution for this? The way its seems just now is that the client cannot call recvfrom without a server being active or it all falls apart. Is there a check that can be done to see if data is sitting on a certain port(data the server would send)? Or is there a better way to do this?

一些代码...

服务器操作——UDPSocket是一个类

Server Operation - UDPSocket is a class

    UDPSocket.Initialise();
    UDPSocket.MakeNonBlocking();
    UDPSocket.Bind(LOCALPORT);
    int n = UDPSocket.Receive(&thePacket);
    if (n > 0)
    UDPSocket.Send(&sendPacket);

客户...

    UDP.Initialise();
    UDP.MakeNonBlocking();
    UDP.SetDestinationAddress(SERVERIP, SERVERPORT);

    serverStatus = UDP.Receive(&recvPacket);    
    if (serverStatus > 0)
    {
        //Do some things
        UDP.Send(dPacket);  //Try and reconnect with server
    }

谢谢

推荐答案

EWOULDBLOCK 本身并不是错误——它只是意味着套接字是非阻塞的,并且没有要读取的数据.我假设您的服务器通过 UDP 侦听数据和回复,并且客户端在启动并接收回复时发送数据包?如果是这样,无论如何你可能会遇到竞争条件——如果服务器正在运行但速度有点慢,然后你在客户端得到 EWOULDBLOCK 怎么办?你的客户会退出吗?也许您想在客户端进行阻塞接收,或者更好的是,使用 select()WaitForMultipleEvents() 或 TCP 或其他东西.

EWOULDBLOCK is not an error per se--it just means the socket was non-blocking and there was no data to read. I presume your server listens for data and replies via UDP, and the client is sending a packet when it starts and receiving the reply? If so, you may have a race condition anyway--what if the server is running but is just a bit slow, and you get EWOULDBLOCK in the client then? Will your client just exit? Perhaps you want to do a blocking receive in the client, or perhaps better yet, use select() or WaitForMultipleEvents() or TCP or something else.

这篇关于UDP:客户端在服务器之前启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆