是否可以同时监听套接字连接并使用不同的端口发送数据? [英] Is it possible to both listening socket connection and send data with different port?

查看:97
本文介绍了是否可以同时监听套接字连接并使用不同的端口发送数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题。我正在开发一个服务器端程序来通过端口X监听传入的套接字连接,并通过端口Y发送数据。我可能通过端口X从机器A收到一个字符串,并且必须将处理结果发送到机器B(或返回到机器)在某些情况下)通过端口Y.

我感到难过,因为我发现在Windows服务程序中很难做到。我可以成功收听,但有时无法发送数据,即使目标机器上的端口Y正在打开。我怎么能解决它?

As title. I am developing a server-side program to listen for incoming socket connections via Port X, and send data via Port Y. I may receive a string from machine A via port X, and must send processed result to machine B (or back to machine A in some case) via port Y.
I felt sad because I found it was hard to do in a windows service program. I can listen successfully but sometimes failed to send data out, even the port Y at the target machine is opening. How could I solve it?

推荐答案

是的,当然,你应该更好地使用单独的线程。您的侦听线程需要使用列出的阻塞调用,并且已经具有连接并写入网络流或从中读取的线程被写入或读取操作阻止。所以每个这样的活动都应该在一个单独的线程中完成。



它还取决于你的应用层协议(总是尝试明确地定义这样的协议)。通常,您有一个协议,要求您以某种常规顺序进行读写,然后这些读取和写入操作是顺序的,将在一个线程中完成;但不是在你听的同一个帖子里。这里的港口无关紧要。如果在一个端口上添加一些活动,则您的线程应与使用另一个端口的线程分开。与此同时,另一个(有点典型的)错误是每个客户端使用一个单独的线程。在服务器端,所有客户端应该更好地提供一个线程,但当然,监听线程应该是分开的。



请查看我过去的答案:

套接字编程中的业余问题 [ ^ ],

来自同一端口的多个客户端号码 [ ^ ],

我如何知道AA Tcp连接结束 [ ^ ] 。



-SA
Yes, of course, but you should better use separate threads for that. Your listening thread needs to use blocking calls to listed, and a thread already having a connection and writing to a network stream or reading from it is blocked by write or read operations. So each such activity should be done in a separate thread.

It also depends on your application-layer protocol (always try to define such protocol explicitly). Typically you have a protocol which requires you to read and write in certain regular order, then such read and write operations, being sequential, will be done in a single thread; but not in the same thread where you listen. The port is irrelevant here. If you add some activity on one port, your threads should be separate from those using another port. At the same time, another (somewhat typical) mistake would be using a separate thread per client. On the server side, all clients should better be served with one thread, but listening thread should be separate, of course.

Please see my past answers:
an amateur question in socket programming[^],
Multple clients from same port Number[^],
How Do I Get To Know If A A Tcp Connection Is Over[^].

—SA


这篇关于是否可以同时监听套接字连接并使用不同的端口发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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