I am new in Android networking and working on project p2p without server.
Initially I have to do communication between 2 devices. I achieved successful communication between two wifi networks within and behind different NATS via DataGramSocket with port forwarding via Upnp using library.
The problem i am facing is while communication between Mobile network and my wifi network or between 2 mobile network. When i send message from mobile network I am unable to receive it in my app but can listen on same port in NetCat app.
Anyone can help me in this regard?
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))
{
}
}