[英]How to send UDP client message in smart way to the UDP server parse the message
[英]How to send UDP message from UDP server without sending to itself?
我想制作一個UDP服務器,該服務器在從客戶端獲取消息后立即向UDP客戶端發送消息。 我正在使用Python和Google Protobuffer作為消息協議。
當前,消息接收部分似乎正常工作,但是對於消息發送部分,它有一個問題:來自服務器的響應消息沒有到達客戶端,甚至更糟的是,服務器顯示了該消息(也許它發送給自己了嗎?現在,控制台將同時顯示來自客戶端的消息和應發送給客戶端的消息。 當我在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編程的經驗不足。 如果您有任何注意事項,請告訴我。
此代碼的問題是服務器回復自身,而不是遠程客戶端。 在這里:
data, address = self.sock.recvfrom(8192)
# ...
bytes_sent = self.sock.sendto(msg_server.SerializeToString(), self.remote)
它應該是:
bytes_sent = self.sock.sendto(msg_server.SerializeToString(), address)
將remote
重命名為server_address
是很有意義的,因為它是該服務器的地址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.