简体   繁体   English

如何在服务器上的线程和客户端上的线程之间同步?

[英]How to synchronize between a thread on server and a thread on client side?

My application creates threads for file transfer on both the server and client sides. 我的应用程序在服务器和客户端上都创建了用于文件传输的线程。 Right now I'm using delaying tactics (a simple for loop) on client side so that thread creation in client is done after the thread creation process in server. 现在,我在客户端使用延迟策略(一种简单的for循环),以便在服务器中的线程创建过程之后完成客户端中的线程创建。

The app works fine. 该应用程序运行正常。 But this is crude, if not ugly. 但这是粗糙的,即使不难看。 I need to find a technical way so that the client thread is not started until it knows that server thread has been started. 我需要找到一种技术方法,以使客户端线程在知道服务器线程已经启动之前才启动。

I tried to use a send() from server to the client. 我尝试使用从服务器到客户端的send()。 The client's recv() must block for server's signal but apparently it doesn't. 客户端的recv()必须阻止服务器的信号,但显然不会。 The message on the client console is about connection being refused by the server. 客户端控制台上的消息是有关服务器拒绝连接的消息。 Any hints, please? 有什么提示吗?

select() may be what you're looking for: you give it a set of sockets and it blocks until something happens on these sockets (and you can provide a timeout to avoid waiting forever). select()可能就是您要寻找的:您给它提供了一组套接字,它阻塞直到这些套接字上发生某些事情为止(并且您可以提供超时以避免永远等待)。
Call select() to wait until data is received on the client side, then recv() to ensure what was received is the right message from the server. 调用select()以等待直到在客户端接收到数据,然后调用recv()以确保接收到的是来自服务器的正确消息。

Seems you use connectionless transport. 似乎您使用无连接传输。 In this case I would suggest playing ping-pong game, client sends "ping" udp packet to server in loop (with reasonable period) until client receives "pong" UDP packet from server or time out. 在这种情况下,我建议您玩乒乓球游戏,客户端将“ ping” udp数据包循环发送到服务器(在合理的期限内),直到客户端从服务器收到“ pong” UDP数据包或超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM