我想在两台机器之间创建一个聊天程序。我正在使用 IP 地址为 192.168.0.5 的机器一,我可以成功地向机器二192.168.0.2 发送一条消息,然后从机器二向机器一发送一条消息作为响应。
但是,我在任何一台机器的第二次发送尝试中遇到了一个问题,(注意到在第二次发送之前我等待初始发送的响应)声称 IP 地址已在使用中或连接被拒绝,这怎么可能更改以便可以发送定义数量的选择?
我很欣赏以下代码不是发送和接收多条消息的最有效方式,这将是 for 循环的一些描述。例如for sendAndRecieve in range(0,5)
.
两台机器使用通过交换机的以太网电缆连接,代码同时运行。
机器 1 代码:
#Sending first message
host = "192.168.0.5"
port = 4446
from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.bind((host,port))
s.listen(1)
print("listening")
q,addr = s.accept(1024)
data = "This is the first message I am sending"
data = data.encode("utf-8")
q.send(data)
s.close
#Recieving response message 1
while True:
try:
host = "192.168.0.2"
port = 4446
from socket import*
s = socket(AF_INET, SOCK_STREAM)
s.connect((host,port))
msg = s.recv(1024)
msg = msg.decode("utf-8")
print(msg)
s.close()
except:
pass
#Sending second message this is where the problem happens
host = "192.168.0.5"
port = 4446
from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.bind((host,port))
s.listen(1)
print("listening")
q,addr = s.accept(1024)
data = "This is the first message I am sending"
data = data.encode("utf-8")
q.send(data)
s.close
机器2代码:
#Recieving message 1
while True:
try:
host = "192.168.0.5"
port = 4446
from socket import*
s = socket(AF_INET, SOCK_STREAM)
s.connect((host,port))
msg = s.recv(1024)
msg = msg.decode("utf-8")
print(msg)
s.close()
except:
pass
#Sending first message
host = "192.168.0.2"
port = 4446
from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.bind((host,port))
s.listen(1)
print("listening")
q,addr = s.accept(1024)
data = "This is the first message I am sending"
data = data.encode("utf-8")
q.send(data)
s.close
#Recieving response message 1 this is where the problem happens
while True:
try:
host = "192.168.0.25"
port = 4446
from socket import*
s = socket(AF_INET, SOCK_STREAM)
s.connect((host,port))
msg = s.recv(1024)
msg = msg.decode("utf-8")
print(msg)
s.close()
except:
pass