如何让服务器接受来自多个端口的连接?

前端之家收集整理的这篇文章主要介绍了如何让服务器接受来自多个端口的连接?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如何创建一个简单的服务器(简单如接受连接并打印到终端接收的任何内容)接受来自多个端口或端口范围的连接?

我是否必须使用多个线程,每个绑定调用一个.还是有其他解决方案吗?

简单的服务器看起来像这样.

def server():
import sys,os,socket

port = 11116
host = ''
backlog = 5 # Number of clients on wait.
buf_size = 1024

try:
    listening_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    listening_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 
    listening_socket.bind((host,port)) 
    listening_socket.listen(backlog)
except socket.error,(value,message):
    if listening_socket:
        listening_socket.close()
    print 'Could not open socket: ' + message
    sys.exit(1)

while True:
    accepted_socket,adress = listening_socket.accept()

    data = accepted_socket.recv(buf_size)
    if data:
        accepted_socket.send('Hello,and goodbye.')
    accepted_socket.close()

server()

编辑:
这是一个如何完成它的例子.感谢大家.

import socket,select

def server():
import sys,socket

port_wan = 11111
port_mob = 11112
port_sat = 11113

sock_lst = []
host = ''
backlog = 5 # Number of clients on wait.
buf_size = 1024

try:
    for item in port_wan,port_mob,port_sat:
        sock_lst.append(socket.socket(socket.AF_INET,socket.SOCK_STREAM))
        sock_lst[-1].setsockopt(socket.SOL_SOCKET,1) 
        sock_lst[-1].bind((host,item)) 
        sock_lst[-1].listen(backlog)
except socket.error,message):
    if sock_lst[-1]:
        sock_lst[-1].close()
        sock_lst = sock_lst[:-1]
    print 'Could not open socket: ' + message
    sys.exit(1)

while True:
    read,write,error = select.select(sock_lst,[],[])

    for r in read:
        for item in sock_lst:
            if r == item:
                accepted_socket,adress = item.accept()

                print 'We have a connection with ',adress
                data = accepted_socket.recv(buf_size)
                if data:
                    print data
                    accepted_socket.send('Hello,and goodbye.')
                accepted_socket.close()

server()
最佳答案
我不是Python人,但你感兴趣的功能是“选择”.这将允许您观察多个套接字,并在其中任何一个发生活动时发生故障.

这是一个python example that uses select.

猜你在找的Python相关文章