我已经开始创建自己的TCP服务器和客户端。我能够让服务器和客户端通过我的LAN网络连接。但是当我尝试让另一个客户端连接以进行三向连接时,它不起作用。只有当第一个连接的客户端终止服务器和客户端之间的连接时,其他客户端才能连接并启动聊天会话。我不明白为什么会这样。我尝试过线程,循环和其他我能想到的东西。我很感激任何建议。我觉得我错过了一件小事,我无法弄清楚它是什么。
import socket
from threading import Thread
def whatBeip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0))
local_ip_address = s.getsockname()[0]
print('Current Local ip: ' + str(local_ip_address))
def clietConnect():
conn, addr = s.accept()
print 'Connection address:', addr
i = True
while i == True:
data = conn.recv(BUFFER_SIZE)
if not data:
break
print('IM Recieved: ' + data)
conn.sendall(data) # echo
whatBeip()
TCP_IP = ''
TCP_PORT = 5005
BUFFER_SIZE = 1024
peopleIn = 4
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(peopleIn)
for client in range(peopleIn):
Thread(target=clietConnect()).start()
conn.close()
import socket
TCP_IP = '10.255.255.3'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
i = True
while i == True:
s.sendall(raw_input('Type IM: '))
data = s.recv(BUFFER_SIZE)
s.close()
答案 0 :(得分:0)
这是你的主要问题:Thread(target=clietConnect()).start()
执行函数clientConnect
并使用它的返回值作为Thread函数(这是None,所以Thread什么都不做)
另请看:
1)您应该等待所有连接关闭而不是服务器末端的conn.close()
:
threads = list()
for client in range(peopleIn):
t = Thread(target=clietConnect)
t.start()
threads.append(t)
for t in threads: t.join()
并在没有收到数据时关闭连接:
if not data:
conn.close()
return
2)您可能想要使用SO_REUSEADDR [Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?,Python: Binding Socket: "Address already in use"]
3)看看asyncio for python