0
我想在兩臺機器之間創建一個聊天程序。我使用機器一個具有IP地址192.168.0.5,我可以成功地將消息發送給機器 192.168.0.2,然後在從機器兩個響應發送消息,向機器1Python中的套接字使用
然而,我在任何一臺機器發出第二次發送嘗試時遇到了問題(注意,在第二次發送之前,我等待初始發送的響應)聲稱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