我们说我有两类客户端和服务器
class Client(Thread):
def __init__(self, serv):
Thread.__init__(self)
self.serv = serv
def run(self):
self.serv.in.put("Hi")
class Server(Thread):
def __init__(self):
Thread.__init__(self)
self.in = Queue()
self.out = Queue()
def run(self):
while True:
if self.in.get():
#smth to do
因此。我创建服务器和客户端,之后,客户端将队列中的启动消息发送到服务器,我可以发回一些东西,等等。
但是,当有2个或3个客户端连接到1个服务器并使用一个队列时,可能会出现一些问题。例如 - 服务器从客户端2读取信息并认为它从客户端3等发起消息
因此,我想为每个客户端创建一个带有in Queue
和out Queue
的新线程,并在第一条消息之后将其发回。所以现在,他们将通过这个新线程与服务器进行通信。
我应该使用in
和out
队列创建新课程并将其发回客户端吗?
我从未使用线程,所以我不知道该怎么做。我试图谷歌它,但发现只有关于创建线程的教程。
答案 0 :(得分:0)
如果你想要的是一个与每个客户端单独通信的服务器,你可以使用服务器实例中的一个控制队列来接收init消息,然后在每个客户端中通过init发送到服务器的进出队列消息。
至于错误消息的风险,我建议使用明确定义的消息结构,使用每种消息类型的类定义。
或许与此相似:
// read in input image and convert to grayscale
Mat frame = imread("fence.png", CV_LOAD_IMAGE_COLOR);
Mat final_out;
frame.copyTo(final_out);
Mat img, gx, gy, mag, angle;
cvtColor(frame, img, CV_BGR2GRAY);
// get the thresholded maggnitude image
Sobel(img, gx, CV_64F, 1, 0);
Sobel(img, gy, CV_64F, 0, 1);
cartToPolar(gx, gy, mag, angle);
normalize(mag, mag, 0, 255, NORM_MINMAX);
mag.convertTo(mag, CV_8U);
threshold(mag, mag, 55, 255.0, THRESH_BINARY);
// apply the hough lines transform and draw the lines
vector<Vec2f> lines;
HoughLines(mag, lines, 1, CV_PI / 180, 240);
for( size_t i = 0; i < lines.size(); i++ )
{
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
pt1.x = 0;
pt1.y = (rho - pt1.x * cos(theta))/sin(theta);
pt2.x = mag.cols;
pt2.y = (rho - pt2.x * cos(theta))/sin(theta);
line(final_out, pt1, pt2, Scalar(0,0,255), 1, CV_AA);
}
// show the image
imshow("final_image", final_out);
cvWaitKey();
答案 1 :(得分:0)
您必须考虑您的要求是什么,您的对象是什么,交换了什么消息以及触发它们的原因。
据我了解,您有一个服务器线程,等待来自客户端的消息,然后将某些内容发送回此客户端。这意味着服务器必须标识其客户端才能向该客户端发送正确的消息。
我的建议是为服务器使用一个队列,为每个客户端使用一个队列。当客户端向服务器发送消息时,它还会将引用传递给应该回发答案的队列。
以下是对您的初始代码的最小更改:
来自队列导入队列的来自线程导入线程
class Client(Thread):
def __init__(self, serv):
Thread.__init__(self)
self.serv = serv
self.inq = Queue() # declares a queue for the client
def run(self):
self.serv.inq.put(("Hi", self.inq)) # send a message, and pass along a response address
resp = self.inq.get() # get the response
print("Got: ", resp)
class Server(Thread):
def __init__(self):
Thread.__init__(self)
self.inq = Queue() # declare a queue for the server
def run(self):
while True:
req = self.inq.get() # get a message from input queue
if not req:
break
msg, clientq = req # parse the message
# other processing
clientq.put("From serv: " + msg) #send back a response
这样,Server
可以为任意数量的不同客户提供服务。但由于服务器本身不是多线程的,因此您一次只能回答一个客户端请求。