我通过Python学习一些网络,并想出了TCPServer Multithread的这个想法,所以我可以连接多个客户端。问题是我只能连接一个客户端。
import socket
import os
import threading
from time import sleep
from threading import Thread
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Preparado...')
def Main():
host = '127.0.0.1'
port = 5000
s.bind((host, port))
print('Enlaze listo...')
print('Escuchando...')
s.listen(5)
c, addr, = s.accept()
os.system('cls')
print('Conexion desde: '+str(addr))
def handle_client(client_socket):
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data: break
print('Client says: ' + data)
print('Sending: ' + data)
client_socket.send(data.encode('utf-8'))
client_socket.close()
if __name__ == '__main__':
while True:
Main()
client_socket, addr = s.accept()
os.system('cls')
print('Conexion desde: '+str(addr))
Thread.start_new_thread(handle_client ,(client_socket,))
s.close()
编辑:这是我的实际代码,为了测试它我打开两个Client.py代码并尝试连接到它。第一个Client.py成功连接(虽然接收和发回信息有错误)第二个执行但它没有在服务器输出中显示为连接或其他东西,它只是编译并保持这样
答案 0 :(得分:2)
每次获得新连接时都需要创建一个新线程
import socket
import thread
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Ready...')
s.bind((host, port))
print('Bind Ready...')
print('Listening...')
s.listen(1)
def handle_client(client_socket):
while True:
data = client_socket.recv(1024)
if not data: break
print('Client says: ' + data)
print('Sending: ' + data)
client_socket.send(data)
client_socket.close()
while True:
client_socket, addr = s.accept()
print('Conexion from: '+str(addr))
thread.start_new_thread(handle_client ,(client_socket,))
s.close()
答案 1 :(得分:0)
好的,这里的代码已经解决了,我应该说我正在研究Python3版本。阅读我发现的文档,这里是代码和文档下方。
import socket
import os
import threading
from time import sleep
from threading import Thread
import _thread
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Preparado...')
def Main():
host = '127.0.0.1'
port = 5000
s.bind((host, port))
print('Enlaze listo...')
print('Escuchando...')
s.listen(1)
def handle_client(client_socket):
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data: break
print('Client says: ' + data)
print('Sending: ' + data)
client_socket.send(data.encode('utf-8'))
client_socket.close()
if __name__ == '__main__':
Main()
while True:
client_socket, addr = s.accept()
os.system('cls')
print('Conexion desde: '+str(addr))
_thread.start_new_thread(handle_client ,(client_socket,))
s.close()
https://docs.python.org/3/library/threading.html http://www.tutorialspoint.com/python3/python_multithreading.htm
问题发生在_thread.start_new_thread(handle_client ,(client_socket,))
只是import _thread
在这里问一些问题,继续研究并得到它。
谢谢你们所有人。
WhiteGlove