在使用服务器/客户端聊天脚本侦听基本端口时遇到了麻烦。 为了对其进行测试,我首先使用服务器运行脚本,然后使用IP 127.0.0.1作为客户端运行脚本 连接到服务器时得到了这个
data,addr = socket.recvfrom(1024)#缓冲区大小为1024字节 OSError:[WinError 10057]
已经尝试编码/解码,禁用防火墙,多种类型的连接设置。
欢迎任何建议。
import socket,sys
serverIP = 'localhost'
UDP_PORT = 12345
print (sys.argv)
if len(sys.argv)==1: #run server
print ('running server')
UDP_IP = serverIP
data = b""
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # UDP
socket.bind(('0.0.0.0',UDP_PORT))
socket.listen(1)
clients = [] # clients list
while True:
client_socket, addr = socket.accept()
clients.append(client_socket) #Add client to list on connection
print (client_socket, " join")
data, addr = socket.recvfrom(1024) # buffer size is 1024 bytes
clientsMngr(clients) #Call external function whenever necessary
data=data.decode()
print (data)
#insert break to quit
else : #run client
print ('running client')
UDP_IP = (sys.argv[1])
userMessage = b""
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # UDP
socket.connect((UDP_IP,UDP_PORT))
while True:
userMessage = input("> ")
userMessage = userMessage.encode()
socket.sendto(userMessage, (UDP_IP, UDP_PORT))
#insert break to quit
def clientsMngr(clients): #Function to manage clients
if len(clients)==0:
None
else :
for client in clients:
socket.connect((client,UDP_PORT))
socket.sendto(data,"(sent by :",(addr),":",(UDP_PORT))
socket.close()
return None