简体   繁体   English

如何使用多线程处理 50 个客户端到服务器

[英]How do I handle 50 clients to server using multithreading

I am using TCP socket for server and client communication.我正在使用 TCP 套接字进行服务器和客户端通信。 The clients are multiple raspberry pi and server is on window. My clients only connect to server when they want to sent the message.客户端是多个树莓派,服务器在 window 上。我的客户端只有在想要发送消息时才连接到服务器。 client act like send receive and disconnect.客户端就像发送接收和断开连接一样。

  1. But my question is how to I communicate if there are 50 to 100 clients.但我的问题是,如果有 50 到 100 个客户,我该如何沟通。
  2. Is it possible to connect if all clients wants to connect at a time to server and if not then how many clients it can connect to server and it depends on what.如果所有客户端都想一次连接到服务器,是否可以连接,如果不是,那么它可以连接到服务器的客户端有多少,这取决于什么。
  3. Can anyone show an python simple example of TCP socket using multithreading handling multiple clients.任何人都可以使用多线程处理多个客户端来显示 python TCP 套接字的简单示例。

It can be done.可以办到。

TCP is actually handled by your OS, not by userspace code. TCP 实际上是由您的操作系统处理的,而不是由用户空间代码处理的。 So the best thing you may do is to kindly ask your OS about it via the (system) calls it exposes.所以你可能做的最好的事情就是通过它公开的(系统)调用向你的操作系统询问它。

As such, OS knows and is prepared for parallel calls from many user-space threads.因此,操作系统知道并准备好接受来自许多用户空间线程的并行调用。 It is protected by an appropriate locking mechanism to ensure serializability.它由适当的锁定机制保护以确保可串行化。

What you should or should not be concerned about is performance and error handling.您应该或不应该关心的是性能和错误处理。 What do you do if the Windows server you have does not accept TCP connection?如果你的Windows服务器不接受TCP连接怎么办? What would you do if it did accept, however TCP retransmission happens over and over again and you can't pass a message?如果确实接受了,你会怎么做,但是TCP重传一遍又一遍,你无法传递消息? What do you do if the Windows service forcibly terminates the connection? Windows服务强行断开连接怎么办? There are many questions to ask in distributed systems.在分布式系统中有很多问题要问。

Performance is another story.性能是另一回事。 You haven't mentioned it, so I won't spend much time on it.你没有提到它,所以我不会花太多时间在这上面。 Let me know if I should though, I'll update the post.让我知道是否应该,我会更新帖子。


Now about Python specifics.现在约Python具体情况。 Due to the "global interpreter lock" in the CPython, multithreading along with its Thread does not make your code truly parallel;由于 CPython 中的“全局解释器锁”, multithreading及其Thread并不能使您的代码真正并行; at best you get single-treaded multitasking a-ka simplest possible concurrency.充其量您可以获得单线程多任务处理,也就是最简单的并发性。 That shouldn't be a big problem for you, since TCP is inherently IO-bound.这对您来说应该不是什么大问题,因为 TCP 本质上是 IO 绑定的。

The simplest you can do is to spawn a dedicated Thread per session. That kinda implies long-living sessions, otherwise, it is a resource waster and performance killer.您可以做的最简单的事情是根据 session 生成一个专用Thread 。这有点意味着长期会话,否则,它是资源浪费和性能杀手。 Again, you did not mention the requirements, so I won't suggest anything.同样,您没有提到要求,所以我不会提出任何建议。

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

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