我试图创建一个连接两台(或更多台)计算机的小聊天程序,所以我尝试了这个:
import socket
tcpSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
tcpSocket.bind(("0.0.0.0",8000))
tcpSocket.listen(3)
print "Waiting for a Client ... "
(client, (ip,sock)) = tcpSocket.accept()
print "Received connection from : ",ip
print "Starting ECHO output ..."
data = 'dump'
client.send("Enter you're name : ")
name=client.recv(1024)
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
client.send("Server : "+send_data)
client.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
print "Closing connection ..."
client.close()
print "Shutting down server ..."
tcpSocket.close()
它运作良好,唯一的问题是我无法将多台计算机连接到服务器!我通过使用这个功能尝试了线程模块:
import socket
import thread
def thread_send() :
print "Received connection from : ",ip
print "Starting ECHO output ..."
data = 'dump'
client.send("Enter you're name : ")
name=client.recv(1024)
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
client.send("Server : "+send_data)
client.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
tcpSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
tcpSocket.bind(("0.0.0.0",8000))
tcpSocket.listen(5)
print "Waiting for a Client ... "
(client, (ip,sock)) = tcpSocket.accept()
for i in range(5) :
thread.start_new_thread(thread_send,())
while True :
pass
print "Closing connection ..."
client.close()
print "Shutting down server ..."
tcpSocket.close()
但它不起作用:/
答案 0 :(得分:-1)
以下是您如何操作的示例。对不起,我没有测试过这段代码,也没有运行它来检查是否有任何语法问题,这只是为了给出一个想法。
def thread_send(cli_sock):
data = 'dump'
cli_sock.send("Enter you're name : ")
name=cli_sock.recv(1024)
if len(name) == 0: ## If client disconnected or terminated
return
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
cli_sock.send("Server : "+send_data)
cli_sock.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_sock.bind(('localhost', 8080))
serv_sock.listen(1)
print "After listen...waiting for accept\n"
try:
while True:
client_sock, address = serv_sock.accept()
print "Connection accepted\n"
thread.start_new_thread(thread_send, (client_sock))
finally:
serv_sock.close()