我找不到唯一的方法来标识服务器上创建和保留的每个线程。每个客户机线程都必须存储自己的信息,这些信息用于将信息中继回其各自的客户机。省略了创建服务器的明显细节:
import sys
from threading import Thread
import socket
import traceback
def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 4096):
while 1:
# the input is in bytes, so decode it
input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE)
if not input_from_client_bytes:
break
# decode input and strip the end of line
input_from_client = input_from_client_bytes.decode("utf8").rstrip()
aString = ''
if (input_from_client.startswith('LOAD BOARD')):
array = input_from_client.split('~')
aString = array[1]
vysl = aString.encode("utf8") # encode the result string
conn.sendall(vysl) # send it to client
conn.close() # close connection
print('Connection ' + ip + ':' + port + " ended")
while True:
conn, addr = soc.accept()
ip, port = str(addr[0]), str(addr[1])
print('Accepting connection from ' + ip + ':' + port)
try:
Thread(target=client_thread, args=(conn, ip, port)).start()
except:
traceback.print_exc()
soc.close()
start_server()
我读到的一个建议是创建一个python文件,并在其中添加所有变量,然后将其导入服务器,但是如果所有其他线程同时编辑这些值,事情就会变得异常。每个线程都希望使用服务器提供的方法。既然数据不能在一个类的方法和另一个类的方法之间交换,那么最好的方法是什么?你知道吗
您可以使用
name
参数为线程命名:Thread(target=client_thread, args=(conn, ip, port), name=str(ip) + ":" + str(port)).start()
相关问题 更多 >
编程相关推荐