[英]Datagram sockets with Java client and Python server
我正在嘗試通過數據報套接字通信2台計算機,但是我想我缺少了一些東西...機器A運行一個Android應用程序(客戶端)機器B是用Python寫的服務器
我可以毫無問題地將消息從A發送到B,但是A從未從B得到答案,代碼如下:
客戶端(Java):
InetAddress serverAddr = InetAddress.getByName("10.0.0.10");
DatagramSocket socket = new DatagramSocket();
byte[] bufSent = "register".getBytes();
DatagramPacket dpSent = new DatagramPacket(bufSent,bufSent.length, serverAddr, 8088);
socket.send(dpSent);
byte[] bufRecv = new byte[1024];
DatagramPacket dpReceive = new DatagramPacket(bufRecv, bufRecv.length);
socket.receive(dpReceive);
String serverMessage = new String(dpReceive.getData(), 0, dpReceive.getLength());
Log.v(LOGTAG, "Received " + serverMessage);
服務器(Python):
import socket
UDP_IP_DEST = "10.0.0.11"
UDP_IP = "10.0.0.10"
UDP_PORT = 8088
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
if data:
print "received message:", data
sock.sendto("I got the message", (UDP_IP_DEST, UDP_PORT))
有人看到錯誤在哪里嗎? 關鍵是我試圖將答案發送到另一台機器而不是移動設備,並且工作正常。
非常感謝。
我在接收時遇到了類似的問題,這是我們在應用程序中使用數據代碼修改了您的值后使用的一些代碼,您可以看到我們在套接字設置中做了一些不同的事情。 mSocket只是一個私有的DatagramSocket成員變量。 試試看。 我認為您可能需要綁定,並可能設置重用地址標志。
try
{
mSocket = new DatagramSocket(null);
mSocket.setReuseAddress(true);
mSocket.setBroadcast(false);
mSocket.bind(new InetSocketAddress(8088));
//Set a 1.5 second timeout for the coming receive calls
mSocket.setSoTimeout(1500);
String data = "myData";
DatagramPacket udpPacket = new DatagramPacket(data.getBytes(), data.length(), InetAddress.getByName("10.0.0.10"), 8088);
mSocket.send(udpPacket);
byte[] buf = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(buf, buf.length);
mSocket.receive(recvPacket);
String response = new String(recvPacket.getData());
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.