0

我想在两台机器之间创建一个聊天程序。我正在使用 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
4

1 回答 1

0

通读您的代码,我看不到机器 2 的 while 循环将如何停止尝试从机器 1 接收数据(循环中没有中断,除非遇到错误)。机器 2 第一次连接后机器 1 确实继续运行,但随后在机器 2 尝试连接机器 1 时尝试连接机器 2。这可能是您看到的错误的原因,也是您只看到的原因发送/接收的第一条消息。

于 2014-07-09T01:18:05.430 回答