本文介绍了多线程服务器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的应该是服务的API在Linux服务器。

I am writing a server in linux that is supposed to serve an API.

首先,我想作一个端口就可以了多线程,这意味着我有多个线程在不同的工作要求一个端口上接收。

Initially, I wanted to make it Multi-threaded on a single port, meaning that I'd have multiple threads working on various request received on a single port.

我的一个朋友告诉我,这不是应该在上班的路上。他告诉我,在收到请求时,我首先必须遵循一个握手程序,创建听献给要求其他端口一个线程,然后重定向要求客户到新的端口。

One of my friends told me that it not the way it is supposed to work. He told me that when a request is received, I first have to follow a Handshake procedure, create a thread that is listening to some other port dedicated to the request and then redirect the requested client to the new port.

从理论上讲,这是非常有趣的,但我无法找到如何实现握手的任何信息,做重定向。有人可以帮忙吗?

Theoretically, it's very interesting but I could not find any information on how to implement the handshake and do the redirection. Can someone help?

如果我没有错间preting您的答复,有一次我创建一个主线程监听端口的多线程服务器,并创建一个新的线程来处理请求,我基本上使得它在多线程单口?

If I'm not wrong in interpreting your responses, once I create a multithreaded server with a main thread listening to a port, and creates a new thread to handle requests, I'm essentially making it multithreaded on a single port?

考虑从哪里获得每秒大量请求的情况。是不是真的该端口在每次请求现在应该等待当前的要求来完成?如果不是,怎么会通信还可以做:说一个浏览器发送一个请求,因此该线程处理这个必须首先侦听的端口,阻止它,处理它,应对和再解锁

Consider the scenario where I get a large number of requests every second. Isn't it true that every request on the port should now wait for the "current" request to complete? If not, how would the communication still be done: Say a browser sends a request, so the thread handling this has to first listen to the port, block it, process it, respond and then unblock it.

这样,eventhough我有多线程,所有我使用的是距主线程因为端口被屏蔽了一次一个单独的线程。

By this, eventhough I'm having "multithreads" , all I'm using is one single thread at a time apart from the main thread because the port is being blocked.

推荐答案

你的朋友告诉你的是类似于被动FTP - 客户端告诉它需要连接的服务器,服务器发回的端口号和客户端创建数据连接到该端口。

What your friend told you is similar to passive FTP - a client tells the server that it needs a connection, the server sends back the port number and the client creates a data connection to that port.

但你想做的是一个多线程的服务器。所有你需要的是一台服务器监听套接字并接受特定端口上的连接。一旦自动TCP握手结束后,你会从获得一个新的socket接受功能 - 即套接字将被用于与刚刚连接的客户端通信。所以,现在你只需要创建一个新的线程,通过该客户端套接字线程函数。在您的服务器线程,然后你会调用接受再次以接受另一个连接。

But all you wanted to do is a multithreaded server. All you need is one server socket listening and accepting connections on a given port. As soon as the automatic TCP handshake is finished, you'll get a new socket from the accept function - that socket will be used for communication with the client that has just connected. So now you only have to create a new thread, passing that client socket to the thread function. In your server thread, you will then call accept again in order to accept another connection.

这篇关于多线程服务器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 21:41
查看更多