Linux多端口监听套接字 [英] multiport listening socket linux

查看:74
本文介绍了Linux多端口监听套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C(linux)编写一个多线程服务器应用程序,该应用程序必须侦听2个不同的端口号,例如侦听端口号3000和4000,以便连接到该客户端的不同客户端提供不同的功能(执行实际功能)通过工作线程,主线程会无限期地运行,并在新的连接上产生新的工作线程).我不确定select是否可以在这里工作,因为我们可以有多个套接字连接,但是所有套接字都与相同的端口号关联.我尝试顺序绑定到sock_1和sock_2.当我运行client_1时,一切正常.但是,当我运行client_2时,我在客户端的connect()上收到错误消息.如果可以在此处使用select(),请告诉我该怎么做.任何帮助,不胜感激!谢谢!

(PS sock_1表示端口号3000,sock_2表示端口号4000,client_1表示从端口3000寻求服务的客户端,client_2表示从同一端口4000寻求服务的客户端)

解决方案

您完全误解了套接字和端口,这是两回事.一个端口可以有多个套接字.但是您可以将列表套接字(被动套接字)绑定到仅一个端口.在进行任何进一步的阅读此

如果您希望您的应用程序在两个不同的端口上侦听,请您将两个不同的套接字与它绑定.

对于快速参考,单个进程中的选择最多只能具有1024个套接字描述符.因此,如果您使用的是单个流程模型,则选择只能处理1024个连接.还要阅读C10k问题,看看什么适合您的需求.

I am writing a multithreaded server application, in C (linux), that must listen to 2 different port numbers, say listen to port no 3000 and 4000, for different clients connecting to it to serve different functionality (actual function is executed by a worker thread, main thread runs indefinitely and spawns of new workers upon new connections). I am not sure if select would work here as we can have multiple socket connections but all associated with same port number. I tried sequentially binding to sock_1 and sock_2. When I run client_1, everything works as expected. But, when I run client_2, I get an error on connect() from client side. If select() can be used here, please let me know how to do it. Any help much appreciated ! Thanks !

(P.S sock_1 refers to port no 3000 and sock_2 refers to port no 4000, client_1 refers to client thats seeking service from port 3000 and client_2 refers to client seeking service from same server from port no 4000)

解决方案

You have totally misunderstood socket and port, these two are different things. A port can have multiple sockets. but you can bind your listing socket(passive socket) to only a single port. Before going any further read this

If you want that your application listen on two different ports, have you bind two different sockets with it.

For a Quick reference a select in single process can only have upto 1024 socket descriptors. So if you are using a single process model then a select can only handle 1024 connections. Also read C10k problem see what suits your need.

这篇关于Linux多端口监听套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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