问题描述
- 有关python socket 多线程问题
- 我现在写的程序是模拟p2p DHT 就是peer1 知道peer2 和 peer3的port 依此类推 现在我写了一个程序 打开的每个xterm端口是一个peer 窗口里可以显示ping所返回的信息
代码如下
我测试了好久 有的显示返回信息 有的显示接收信息 有的豆显示 有的根本不显示
刚学编程半年 python很多东西不了解 socket 和多线程完全是先学先用的 所以请各位看一下
到底问题出在哪里以下是代码
import sys
import time
import socket
import threadingclass peer_server(threading.Thread):
def init(self):
threading.Thread.__init__(self)
self.ID = None
self.port = None
def run(self):
print(self.port)
server_port = self.port
serverSocket = socket.socket(socket.AF_INET socket.SOCK_DGRAM)
serverSocket.bind(('' server_port))
while 1:
message clientAddress = serverSocket.recvfrom(2048)
sendMessage = 'A ping response message was received from Peer {:}'.format(self.ID)
serverSocket.sendto(sendMessage.encode('ascii') clientAddress)
print('server {:}'.format(self.ID))
print(message.decode('ascii'))
print(time.time())class peer_client(threading.Thread):
def init(self):
threading.Thread.__init__(self)
self.ID = None
self.port1 = None
self.port2 = Nonedef run(self): while 1: server_port = self.port1 clientSocket = socket.socket(socket.AF_INET socket.SOCK_DGRAM) sendMessage = 'A ping request message was received from Peer {:}'.format(self.ID) clientSocket.sendto(sendMessage.encode('ascii')('' server_port)) receiveMessage serverAddress = clientSocket.recvfrom(2048) print('client {:}'.format(self.ID)) print(receiveMessage.decode('ascii')) print(time.time()) clientSocket.close() server_port = self.port2 clientSocket = socket.socket(socket.AF_INET socket.SOCK_DGRAM) clientSocket.sendto(sendMessage.encode('ascii')('' server_port)) receiveMessage serverAddress = clientSocket.recvfrom(2048) print('client {:}'.format(self.ID)) print(receiveMessage.decode('ascii')) print(time.time()) clientSocket.close() time.sleep(5)
class peer(threading.Thread):
ID = None
port = None
port1 = None
port2 = None
def init(self ID fID sID):
self.ID = ID
self.port = 50000 + ID
self.port1 = 50000 + fID
self.port2 = 50000 + sID
def start_server(self):
server = peer_server()
server.ID = self.ID
server.port = self.port
server.start()
def ping(self):
client = peer_client()
client.ID = self.ID
client.port1 = self.port1
client.port2 = self.port2
client.start()p0 = peer(int(sys.argv[1]) int(sys.argv[2]) int(sys.argv[3]))
p0.start_server()
p0.ping()
解决方案
xterm -hold -title ""Peer 1"" -e ""python3 cdht.py 1 3 4"" &
xterm -hold -title ""Peer 3"" -e ""python3 cdht.py 3 4 5"" &
xterm -hold -title ""Peer 4"" -e ""python3 cdht.py 4 5 8"" &
xterm -hold -title ""Peer 5"" -e ""python3 cdht.py 5 8 10"" &
xterm -hold -title ""Peer 8"" -e ""python3 cdht.py 8 10 12"" &
xterm -hold -title ""Peer 10"" -e ""python3 cdht.py 10 12 15"" &
xterm -hold -title ""Peer 12"" -e ""python3 cdht.py 12 15 1"" &
xterm -hold -title ""Peer 15"" -e ""python3 cdht.py 15 1 3"" &
测试的所需要的代码
在terminal输入
解决方案二:
关于python的多线程问题
python 多线程问题
Python中socket和多线程的应用