android udp服务,Android UDP对等网络通信(无服务器)
我是Android网络的新手,在没有服务器的情况下处理项目p2p .最初我必须在2台设备之间进行通信 . 我通过DataGramSocket实现了在不同NATS内部和后面的两个wifi网络之间的成功通信,并通过Upnp使用library进行端口转发 .我面临的问题是移动网络和我的wifi网络之间或2移动网络之间的通信 . 当我从移动网络发送消息时,我无法在我的应用程序中收到它,但可以在NetCat
我是Android网络的新手,在没有服务器的情况下处理项目p2p .
最初我必须在2台设备之间进行通信 . 我通过DataGramSocket实现了在不同NATS内部和后面的两个wifi网络之间的成功通信,并通过Upnp使用library进行端口转发 .
我面临的问题是移动网络和我的wifi网络之间或2移动网络之间的通信 . 当我从移动网络发送消息时,我无法在我的应用程序中收到它,但可以在NetCat应用程序中的同一端口上收听 .
谁能在这方面帮助我?
Sending
try {
socket = new DatagramSocket(dstPort);
address = InetAddress.getByName(dstAddress);
socket.connect(address,dstPort);
socket.setBroadcast(false);
socket.setReuseAddress(true);
//sendState("Socket Status "+socket.isConnected());
String sendString = msg;
byte[] sendData = sendString.getBytes("UTF-8");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
address, dstPort);
socket.send(sendPacket);
//sendState("Sent = "+sendData);
} catch (SocketException e) {
//sendState(e.getLocalizedMessage());
sendState("SocketException");
}
Receiving
try {
socket = new DatagramSocket(dstPort);
address = InetAddress.getByName(dstAddress);
// send request
byte[] buf = new byte[4096];
DatagramPacket packet =
new DatagramPacket(buf, buf.length, address, dstPort);
socket.connect(address,dstPort);
socket.setBroadcast(false);
socket.setReuseAddress(true);
socket.receive(packet);
String line = new String(packet.getData(), 0, packet.getLength());
sendState(line);
//sendState("Reached3");
} catch (SocketException e) {
//sendState(e.getLocalizedMessage());
sendState("SocketException");
}
Port Forwarding via UpNp
protected void setUpnp(int port_)
{
if(Connectivity.isConnectedWifi(this)) {
String myIp = getIpAddress();
int port = port_;
//creates a port mapping configuration with the external/internal port, an internal host IP, the protocol and an optional description
PortMapping[] desiredMapping = new PortMapping[2];
desiredMapping[0] = new PortMapping(port, myIp, PortMapping.Protocol.TCP);
desiredMapping[1] = new PortMapping(port, myIp, PortMapping.Protocol.UDP);
//starting the UPnP service
UpnpService upnpService = new UpnpServiceImpl(new AndroidUpnpServiceConfiguration());
RegistryListener registryListener = new PortMappingListener(desiredMapping);
upnpService.getRegistry().addListener(registryListener);
upnpService.getControlPoint().search();
}
else if(Connectivity.isConnectedMobile(this))
{
}
}
更多推荐
所有评论(0)