我是Python的初学者,今天我尝试创建一个简单的聊天程序。到目前为止,它并没有太糟糕,但我无法在服务器和客户端之间进行通信。我只能从服务器发送到客户端,但不能从另一个方向发送。我尝试使用多线程,结果如下:
服务器
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.bind((host, port))
s.listen(3)
conn, addr = s.accept()
print("Connection from: "+str(addr[0])+":"+str(addr[1]))
def recv_data():
while True:
data = s.recv(2048).decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(socket.gethostname())+"> ")
msg = str(host + "> ").encode('utf-8') + msg.encode('utf-8')
conn.send(msg)
#t1 = threading.Thread(target=recv_data)
t2 = threading.Thread(target=send_data)
#t1.start()
t2.start()
客户端:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.connect((host, port))
print("Connected to: "+ host)
def recv_data():
while True:
data = s.recv(2048)
data = data.decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(host)+"> ").encode('utf-8')
s.send(msg)
t1 = threading.Thread(target=recv_data)
#t2 = threading.Thread(target=send_data)
t1.start()
#t2.start()
此代码有效;服务器可以发送,客户端接收,但每当我取消注释第二个线程,这样它可以做到这两个我得到一个错误:
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
我似乎无法找到解决方案,所以请帮忙,我做错了什么? :d
答案 0 :(得分:0)
conn, addr = s.accept() def recv_data(): while True: data = s.recv(2048).decode('utf-8') print(data)
conn
实际上是您要send
或recv
要使用的套接字。发生该错误是因为您试图从服务器套接字recv
,这是非法操作。因此,如果要使其工作,则需要将s
更改为conn
。