问题描述
因此,我目前正在尝试使用Python 3.8创建服务器/客户端系统。 我试图使其处理多个客户端,但仍然不能同时连接两个或多个客户端。 我试过了 : 创建一个函数以在服务器运行时接受任何传入的连接 使代码“监听”传入的连接并接受它们(如果不存在连接,将阻止代码运行)。 预先感谢您的帮助,祝您有个美好的一天:)
这是有问题的代码:
import socket
from datetime import datetime
import os
import random
import sys
import time
from threading import Thread
#defining functions for later use
def conn_join():
try:
sock.listen(5)
client,addr = sock.accept()
except:
return None
hostname = socket.gethostname() # We automatically get the host's IP to
HOST = socket.gethostbyname(hostname) # make it easier to connect
print("Session hosted on host ",HOST)
host_ask = input("Set the server on host mode ? y/n \n")
if host_ask == 'y':
host = True
print("Server defined as host")
else :
host = False
print("Server not hosting session,participating")
#def on_new_client(clientsocket,addr):
while True:
msg = clientsocket.recv(1024)
print(addr,' >> ',msg)
msg = raw_input('SERVER >> ')
clientsocket.send(msg)
clientsocket.close()
PORT = 6789 # We tell the server what port we want it on
max_size = 1028 # Prevent overloading
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((HOST,PORT)) # These lines basically "start" the exchange
sock.listen(5)
client,addr = sock.accept() # This allows for data exchange
sock.setblocking(False)
print("Starting the server at :",datetime.now())
print("Waiting for connection from client") # We tell the user when the server started
print("Starting security protocol") # We run a security protocol. If the
code = random.randint(1000,10000) # client somehow gets the code
print("Here's the code : ",code) # wrong/isn't supposed to be there,the
code_attempt = client.recv(max_size) # connection will be terminated
code_attempt = code_attempt.decode('utf-8') # We decode the answer from the client
print(code_attempt,"-Attempt - Code-",code)
time.sleep(1)
for code in code_attempt:
security = True
print("/!/ Client is clear for connection /!/")
break
else :
security = False
print("/!/ Client had a wrong code /!/") # The server will terminate
print("/!/ Terminating connection /!/") # the connection
while security==True and host==False:
conn_join()
data = client.recv(max_size)
print("At",datetime.now(),addr," said",data.decode('utf-8')) # We use the utf-8 encoding
message_to_client = input("Enter message to client :\n")
message_to_client_encoded = message_to_client.encode('utf-8')
client.send(message_to_client_encoded)
while security==True and host==True:
conn_join()
data = client.recv(max_size)
data_received = data.decode('utf-8')
print("At",data_received) # We use the utf-8 encoding
message_to_client_back = data
client.send(message_to_client_back)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)