0
我想製作一個UDP服務器,在服務器從客戶端收到消息後,立即向UDP客戶端發送消息。我使用Python和Google Protobuffer作爲消息協議。如何從UDP服務器發送UDP消息而不發送給自己?
目前,消息接收部分似乎工作,但關於消息發送部分,它有一個問題:來自服務器的響應消息沒有到達客戶端,甚至更糟糕的是,服務器顯示該消息(可能它發送自己?現在,控制檯顯示來自客戶端的消息和應發送給客戶端的消息)。當我在C++或C#上嘗試類似的代碼時,這個問題沒有發生。
以下是從我的代碼中的一些摘錄:
def connect(self):
remote = ('x.x.x.x',xxxx) #ip and port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(2.5)
self.sock.bind(remote)
self.sock.settimeout(None)
def start(self):
while not self.exit_thread:
# Get the message from client
data, address = self.sock.recvfrom(8192)
if data is not None:
# De-serialize inbound message from client
msg_client = xxx_pb2.msgClient()
msg_client.ParseFromString(data)
# Display message from client
self.display_inbound_message(msg_client)
# Create a new message from server
msg_serer = xxx_pb2.msgServer()
self.create_outbound_message(msg_serer)
# Send the Udp message to the client, return the number of bytes sent
bytes_sent = self.sock.sendto(msg_server.SerializeToString(), self.remote)
if (bytes_sent < 0):
print("Error send message")
我沒有有關Python編程UDP足夠的經驗。如果您發現任何問題,請告訴我。
你如何調用這個函數?在'線程'還是不是? – Arman
我現在不使用'thread',但打算在解決這個問題後使用它。它與這個問題有關嗎? – kangaroo