Receive UDP packets in Async Task BackGround Process - java

protected String doInBackground(String... f_url) {
int count;
byte [] ip_bytes = new byte[] {(byte)192,(byte)168,(byte)1,(byte)100};
try {
InetAddress address = InetAddress.getByAddress(ip_bytes );
byte buffer[] = new byte[2000];
DatagramPacket p = new DatagramPacket(buffer, buffer.length, address, port);
try {
DatagramSocket ds = new DatagramSocket(port);
Log.d("..........","Perfect Binding .... Waiting for Data");
ds.receive(p);
publishProgress(""+p);
Thread.sleep(100);
Log.d("","Received :) ");
} catch(Exception e)
{
e.printStackTrace();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
....................................
This is code for receiving UDP packet in Async Backgroung Process, But am not getting a single packet ... what is wrong in my code ?? How i can overcome this problem ?

It seems for receiving, you don't need to specify the ip and port in DatagramPacket.
DatagramPacket p = new DatagramPacket(buffer, buffer.length);

Related

Sending Unicast packets to a Multicast port

I have a Multicast socket open and is receiving Multicast message. From this thread, it seems that the same multicast socket should also be able to receive unicast messages. However, I'm not able to get anything.
Edit: the port number seems the be problem. Port 3702 is used by ws-discovery for unicasting which is related to what I'm trying to do. I'm tracking down a problem where the client's probe to the service is not caught by the service's multicast socket. I'm running this on windows.
My multicast server:
class Server extends Thread {
MulticastSocket multicastSocket;
final Logger LOG;
final int PORT = 3702;
final String MULTICAST_ADDR = "239.255.255.250";
InetAddress multicastGroup;
public Server() {
LOG = Logger.getLogger("Server");
try {
multicastGroup = InetAddress.getByName(MULTICAST_ADDR);
multicastSocket = new MulticastSocket(PORT);
multicastSocket.setInterface(InetAddress.getLocalHost());
multicastSocket.joinGroup(multicastGroup);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (!Global.exit) {
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
try {
multicastSocket.receive(recv);
String msg = new String(recv.getData(), StandardCharsets.UTF_8);
LOG.log(Level.INFO, "got: " + msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the client code:
public void directMsgTest(){
try {
DatagramSocket datagramSocket = new DatagramSocket( 8080,InetAddress.getLocalHost());
String msg = "direct msg";
byte[] buf = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), DST_PORT);
datagramSocket.send(packet);
datagramSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It seems that this is Window's fault. It uses WS discovery in some of its services, thus using port 3702 and eating unicast packets send to port 3702 instead of giving it to my server.
I tried running this on Linux and it was fine.

TCP data sending each 20ms issue

I'm trying to send data through UDP each 20ms and It's working properly.
But, as I try to use TCP it's not working well and the app gives me the not responding error!
Following code is for sending through UDP
public class sMessage implements Runnable {
#Override
public void run() {
try {
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("192.168.16.254");
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
s.send(p);
} catch (IOException e) {
Log.e(TAG, "ERROR");
}
}
}
And I use the same Runnable for TCP, but not working correctly!
public class sMessage implements Runnable {
#Override
public void run() {
try {
Log.v(TAG, "send");
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Socket socket = new Socket(serverAddr, 5000);//create a socket
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
PrintWriter ot = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String s = "1";
//s+="\r\n";
//byte[] bytes = s.getBytes("UTF-8");
//os.writeChar(1);
//os.writeBytes(text);
//os.writeUTF(String.valueOf("123"));
ot.println(text);
ot.flush();
ot.close();
os.flush();
os.close();
socket.close();
} catch (IOException e) {
Log.e(TAG, "ERROR");
}
}
}
My goal is to send data each 10ms by using TCP!
why it is not working properly!??
Thanks in advance for your replies

Can't receive String from UDP multicast

I'm having some problems receiving a String from a multicast.
It's the first time i'm using UDP multicast in Java.
I'm making a multiclient application over a LAN.
So i'm using Local Ip addresses.
I need the clients to find the server's IP address so they can send their data, requests, etc.
I let the server sent out a multicast with his own IP as a string every 5 seconds.
The clients should be able to receive it.
The problem is that they don't receive anything.
I'm testing with 2 devices so i don't need to use localhost.
Here's some of my code:
Server side:
public class MulticastIpSender extends Thread{
private String serverIp;
private int port;
private String multicastAddress;
private long WAITING_TIME = 5000; // 5 seconden
private DatagramSocket socket;
public MulticastIpSender(String serverIp, int port, String multicastAddress) throws SocketException {
super();
this.serverIp = serverIp;
this.port = port;
this.multicastAddress = multicastAddress;
socket = new DatagramSocket(port);
}
public void run() {
while(true){
try {
byte[] buf = new byte[256];
buf = serverIp.getBytes();
InetAddress group = InetAddress.getByName(multicastAddress);
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
socket.send(packet);
System.out.println("sent IP("+serverIp+") to group("+group+") on port "+port);
sleep(WAITING_TIME);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I put this method in the main class:
private void sendIpAddressToListeners() {
try {
multicastIpSender = new MulticastIpSender(serverIp,PORT,"230.0.0.1");
multicastIpSender.run();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get the serverIp like this:
String hostName = InetAddress.getLocalHost().getHostName();
InetAddress addrs[] = InetAddress.getAllByName(hostName);
if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress()) {
myIp = addr.getHostAddress();
}
}
System.out.println ("\nIP = " + myIp);
return myIp;
on this device it gives me 192.168.1.2
CLIENT SIDE:
multicastSocket = new MulticastSocket(PORT);
InetAddress address = InetAddress.getByName(MULTICAST_ADDRESS);
multicastSocket.joinGroup(address);
DatagramPacket serverIpPacket;
byte[] buf = new byte[256];
serverIpPacket = new DatagramPacket(buf, buf.length);
while(receivedIp ==null){
multicastSocket.receive(serverIpPacket);
receivedIp = new String(serverIpPacket.getData(), 0, serverIpPacket.getLength());
System.out.println("received server ip: " + receivedIp);
}
!! PORT = 4445 in both server and client
I hope somebody can help me with this or can explain a better way to do this.
Send a normal DatagramPacket on broadcast address, the packet will be received by all hosts in local network (with same network configuration, important part is mask)
Use calculator to check your broadcast address, this one works good: http://www.subnet-calculator.com/

set timeout for socket receive

I want to send data to server, then wait for an answer for one minute and then close the socket.
How to do it?
DatagramPacket sendpack = new ......;
socket.send(pack);
DatagramPacket recievepack = new .....;
//wait 1 minute{
socket.recieve(buf);
//wait 1 minute}
socket.close();
You can try this. Change the timeout of the socket as required in your scenario! This code will send a message and then wait to receive messages until the timeout is reached!
DatagramSocket s;
try {
s = new DatagramSocket();
byte[] buf = new byte[1000];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
InetAddress hostAddress = InetAddress.getByName("localhost");
String outString = "Say hi"; // message to send
buf = outString.getBytes();
DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999);
s.send(out); // send to the server
s.setSoTimeout(1000); // set the timeout in millisecounds.
while(true){ // recieve data until timeout
try {
s.receive(dp);
String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": "+ new String(dp.getData(), 0, dp.getLength());
System.out.println(rcvd);
}
catch (SocketTimeoutException e) {
// timeout exception.
System.out.println("Timeout reached!!! " + e);
s.close();
}
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
//e1.printStackTrace();
System.out.println("Socket closed " + e1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you are using DatagramSocket, or Socket you can use,
socket.setSoTimeout(1000);
//the value is in milliseconds
For any detail, you should've taken a look in DatagramSocket javadoc or Socket javadoc.
To clarify EJP's comment, this is what he meant by a "missing break" causing a SocketException.
String group = "224.0.0.0";
int port = 5000;
MulticastSocket recvSock = new MulticastSocket(port);
recvSock.joinGroup(InetAddress.getByName(group));
recvSock.setSoTimeout(1000);
while(true) {
try {
recvSock.receive(in);
} catch (SocketTimeoutException e) {
break; // Closing here would cause a SocketException
}
}
// Move the close() outside the try catch bloock
recvSock.leaveGroup(InetAddress.getByName(group));
recvSock.close();

Multicasting in Java not working

I'm developing some peer 2 peer app for my class and I was told for letting servers to discover each other they have to Multicast to their UDP port 1110 and listen to their UDP port 1110. I wrote the code like below for doing that. for testing I run 2 servers which both send and receive. but it seems nothing working. where do you think my problem is ?
I put 2 servers in 2 different folders. and I assigned to IP addresses to my NIC like this ifconfig eth0:3 192.168.0.11 netmask 255.255.255.0 up how should I tell each server about the new ip address?
BroadcastListner
class BroadcastListner implements Callable<Object> {
int PORT = 1110;
String IP = "255.255.255.255";
MulticastSocket socket ;
DatagramPacket packet;
InetAddress IPAD;
byte data[] = null ; //////////////change size
int numOfNodes;
BroadcastListner(String IP, int numOfNodes) {
try {
this.numOfNodes = numOfNodes;
this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket(PORT);
packet = new DatagramPacket(data,data.length);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastListner(int numOfNodes) {
try{
this.numOfNodes = numOfNodes;
// this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket(PORT);
packet = new DatagramPacket(data,data.length);
} catch (Exception e) {
e.printStackTrace();
}
}
public String call() {
try{
socket.joinGroup(IPAD);
} catch (Exception e) {
e.printStackTrace();
return "";
}
while(true) {
try {
socket.receive(packet);
String str = new String(packet.getData());
System.out.println(" Time signal received from"+
packet.getAddress() + " Time is : " +str);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
//socket.leaveGroup(IPAD);
//socket.close();
//return "";
}
}
BroadcastSender
class BroadcastSender implements Callable<Object> {
int PORT = 1110;
String IP = "255.255.255.255";
MulticastSocket socket;
DatagramPacket packet;
InetAddress IPAD;
byte[] data = "IAmAServer".getBytes();
//int numOfNodes;
String str = "IAmAServer";
BroadcastSender(String IP) {
try {
// this.numOfNodes = numOfNodes;
this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket();
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastSender() {
try{
// this.numOfNodes = numOfNodes;
// this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket();
} catch (Exception e) {
e.printStackTrace();
}
}
public String call() {
try {
socket.joinGroup(IPAD);
socket.setTimeToLive(10);
} catch (Exception e) {
e.printStackTrace();
return "";
}
while(true) {
try {
Thread.sleep(2000);
packet = new DatagramPacket (data,str.length(),IPAD,PORT);
socket.send(packet);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
//return "";
}
}
You need to try the broadcast address of 192.168.0.255
An alternative is to use a multi-cast instead of broadcast address like 224.x.x.x which is not tied to a specific subnet.

Categories