[英]How to make a TCP server handle multiple clients?
我正在嘗試制作一個可以連接多個客戶端的Python服務器,但是遇到了一個問題,我嘗試了在互聯網上找到的所有內容。 我正在運行Windows 7和I3處理器的筆記本電腦。
這是名為tcp的文件:
import socket
def make_server (ip,port):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((ip, port))
server.listen(1)
return server
except Exception as ex:
print(ex)
return None
def accept(server):
conn, addr = server.accept()
return conn
def make_client():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return client
def client_connect(client,ip,port):
client.connect((ip,port))
def sendall(conn,mess):
conn.send(str(mess).encode("utf-8"))
def rec(conn,rate):
mess = conn.recv(rate).decode("utf-8")
return mess
def close(client):
client.close()
這是服務器 :
from multiprocessing import Process
from random import randint
import tcp
import sys
def start(sip, sport):
print("Making sob server...")
print("id= {}".format(sport))
sserver = tcp.make_server(sip, sport)
print("Sub Server Started!")
sconn = tcp.accept(sserver)
tcp.sendall(sconn, "connected!!")
while True:
try:
tcp.sendall(sconn, randint(0, 100))
except Exception as ex:
print("")
print("From server {} error:".format(port))
print(ex)
print("")
break
ip = "192.168.0.102"
port = 8000
subport = 9000
server = tcp.make_server(ip, port)
if server is None:
sys.exit(0)
print("Started!")
while True:
print("Wating for new connection!")
con = tcp.accept(server)
print("Connected!")
subport = subport + 1
tcp.sendall(con, subport)
print("New Port Sent!")
print("New Port = {}".format(subport))
subs = Process(target=start, args=(ip, subport))
subs.start()
subs.join()
這是客戶 :
import tcp
import time
nport = 0
ip = "192.168.0.102"
port = 8000
client = tcp.make_client()
tcp.client_connect(client,ip,port)
nport = tcp.rec(client,1024)
print(nport)
tcp.close(client)
nport = int(nport)
time.sleep(1)
print(nport)
client = tcp.make_client()
tcp.client_connect(client,ip,nport)
while True:
mess = tcp.rec(client, 1024)
if(mess):
print(mess)
錯誤是:
[WinError 10048]Only one usage of each socket address (protocol/network address/port) is normally permitted Python
隨時更改您想要的任何內容。 如果您需要任何信息,請詢問。
您正在使用tcp.make_client
在客戶端中創建套接字。 然后,您將使用該套接字通過tcp.client_connect
連接到服務器。 大概您已經成功從服務器收到了新的端口號。 但是,然后您嘗試重新使用同一套接字來連接到那些端口。
這是導致錯誤的直接原因:套接字只能用於單個TCP連接。 如果要創建新的連接,則必須首先創建一個新的套接字。
話雖如此,如果您只是嘗試創建一個可以接受多個連接的服務器,那么您將使其變得過於復雜。 只要每個客戶端使用不同的地址/端口組合,服務器就可以在其單個偵聽端口上接收任意數量的連接。
在服務器中構造此文件的一種方法是這樣的:
# Create and bind listening socket
lsock = socket.socket()
lsock.bind(('', port))
lsock.listen(1)
while True:
csock, addr = lsock.accept()
print("Got connection from {}".format(addr))
# Start sub-process passing it the newly accepted socket as argument
subs = Process(target=start, args=(csock, ))
subs.start()
# Close our handle to the new socket (it will remain open in the
# sub-process which will use it to talk to the client)
csock.close()
# NOTE: do not call subs.join here unless you want the parent to *block*
# waiting for the sub-process to finish (and if so, what is the point in
# creating a sub-process?)
還有其他幾種方法可以執行此操作:您可以創建多個線程來處理多個連接,或者可以使用select
或異步I / O處理單個線程中的所有連接。
客戶端通常要簡單得多-因為它通常只關心自己的一個連接-並不關心服務器的實現方式:
sock = socket.socket()
sock.connect((ip, port))
while True:
sock.send(...)
sock.recv(...)
如果客戶端確實希望再次連接到同一服務器,則只需創建第二個套接字並使用相同的服務器IP和端口調用其connect
方法。
通常,客戶端不需要指定自己的端口,而只需指定服務器的端口。 它只是簡單地調用connect
,而客戶端操作系統會為其選擇一個未使用的端口。 因此,客戶端第一次創建套接字並將其連接(連接到服務器的偵聽端口 ),客戶端操作系統可能會選擇端口50001。下次創建並連接套接字時,它將獲得50002,依此類推。 (選擇的確切端口號取決於操作系統的實現和其他因素,例如正在運行哪些其他程序並創建連接。)
因此,給定客戶端IP 192.168.0.101和服務器IP 192.168.0.102,並假設服務器正在偵聽端口8000,這將導致以下兩個連接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.