I want to execute a udp receiver on eclipse. But its not working. The udp sender works properly and the packets are sent through the specific port. But emulator is not able to receive any packets through a udp sender. Help needed.
i don't know what your scenario is but according to my scenario i just setup a UDP server on my system(Windows 7) using php script and successfully sended and received UDP packets from android emulator with the following code.
String receivedString="";
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sendData = stringToBeSended.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
DatagramSocket clientSocket;
try {
clientSocket = new DatagramSocket();
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
receivedString = new String(receivePacket.getData());
clientSocket.close();
} catch (SocketException e) {
Log.v("SocketExceptionOccured", e.toString())
e.printStackTrace();
} catch (IOException e) {
Log.v("IOExceptionOccured", e.toString())
e.printStackTrace();
}
Toast.makeText(getBaseContext(), receivedString, Toast.LENGTH_LONG).show();
Related
I'm trying to broadcast udp packets between two Android devices on a hotspot.
I have a client that set up the hotspot, and a server that is connected to the hotspot. Sending a package from the client and receiving that packet on the server is working. But when I try to reply from the server, I get a SocketException, saying network is unreachable. I've checked the IP address and port number and both should be correct (I'm assuming the port is correct because it was taken from the packet itself).
The code for the server and client is below. Can anyone see where the code is going wrong or if it's just a network connectivity issue?
Client:
try {
//Open a random port to send the package
c = new DatagramSocket();
c.setBroadcast(true);
byte[] sendData = "DISCOVER_MV_REQUEST".getBytes();
try {
InetAddress addr = getIpAddress();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, getBroadcast(addr), 8888);
c.send(sendPacket);
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
// Broadcast the message over all the network interfaces
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue; // Don't want to broadcast to the loopback interface
}
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null) {
continue;
}
// Send the broadcast package!
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
c.send(sendPacket);
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
}
}
//Wait for a response
byte[] recvBuf = new byte[15000];
DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
c.receive(receivePacket);
//Check if the message is correct
String message = new String(receivePacket.getData()).trim();
if (message.equals("DISCOVER_MV_RESPONSE")) {
//DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
Log.v("SOCKET", "got correct response");
c.close();
return "correct";
} else {
c.close();
Log.v("SOCKET", "wrong response");
return "wrong";
}
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
Server:
try {
//Keep a socket open to listen to all the UDP trafic that is destined for this port
socket = new DatagramSocket(8888, InetAddress.getByName("0.0.0.0"));
socket.setBroadcast(true);
while (true) {
//Receive a packet
byte[] recvBuf = new byte[15000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(packet);
//See if the packet holds the right command (message)
String message = new String(packet.getData()).trim();
if (message.equals("DISCOVER_MV_REQUEST")) {
byte[] sendData = "DISCOVER_MV_RESPONSE".getBytes();
//Send a response
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
socket.send(sendPacket); //where the error happens
socket.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
I have a box, which sends UDP response after receiving UDP packet.
I finally found example
how to implement UDP server.
It receives UDP packets okay.
There is a button in my app.
If I tap it I sends UDP packet to the box,
but I don't get the resonse.
I see that the box receives this packet
from my Android device and sends the response.
My UDP client is below:
public class AsyncSendUdp extends AsyncTask<String, Void, Boolean> {
InetAddress inet_addr;
DatagramSocket socket;
#Override
protected Boolean doInBackground(String... arg0) {
byte[] ip_bytes = new byte[]{(byte) 192, (byte) 168, (byte) 0, (byte) 11};
try {
inet_addr = InetAddress.getByAddress(ip_bytes);
} catch (UnknownHostException e) {
e.printStackTrace();
}
char[] bufc = {1, 2, 3, 4};
byte[] buffer = new byte[4];
for (int i = 0; i < 4; i++) {
buffer[i] = (byte) bufc[i];
}
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, inet_addr, 0xbac0);
try {
socket = new DatagramSocket();
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
I send as follows:
new AsyncSendUdp().execute("mmm");
I don't understand where is the problem.
Any ideas please!
You're never actually reading for incoming messages. You'll want something like:
byte[] inBuffer = new byte[N];
DatagramPacket inPacket = new DatagramPacket(inBuffer, inBuffer.length);
while (!exitCondition) {
socket.receive(inPacket);
// do something with your received packet
}
I was working on a application where i needed to establish a communication between android and PC to transfer some data over wi-fi. I am able to communicate between two PC's over wifi. So code from PC side is ready. I needed a reference to use Wifi from android side. Something similar to bluetooth chat is helpful. I am able to scan Wifi networks present in android but not able to proceed further.
Cheers
This one receives a file
private String ReceiveFile() {
try {
ServerSocket socket = new ServerSocket(port);
socket.setSoTimeout(5000);
Socket os = null;
try {
os = socket.accept();
} catch (SocketTimeoutException t) {
if (!socket.isClosed()) socket.close();
return "TIMEOUT";
}
InputStream bos = os.getInputStream();
FileOutputStream fos = new FileOutputStream(FILENAME);
DataOutputStream bw = new DataOutputStream(fos);
int Total = 0;
byte[] buffer = new byte[4096];
int read;
while (true) {
read = bos.read(buffer);
if (read <= 0) break;
bw.write(buffer, 0, read);
Total = Total + read;
}
if (!socket.isClosed()) socket.close();
return "SUCCESS";
} catch (Exception e) {
e.printStackTrace();
return "FAILURE";
}
}
Without knowing what you trying to achieve it is difficult to be more specific but this snippet receives a short data burst.
DatagramSocket serverSocket = new DatagramSocket(PORTNUMBER);
byte[] receiveData = new byte[50];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.setSoTimeout(5000);
serverSocket.receive(receivePacket);
serverSocket.close();
i want to send data(latitude and longitude )to a web server (windows server 2008) who"s ip and udp port is known from my android application .how to do so ?
here is a sample code which i m trying but data is not received to other end
public class UDPServer extends Activity {
WebView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState) ;
setContentView(R.layout.main);
view=(WebView) findViewById(R.id.webView1);
try {
String serverHostname = new String ("ip and udp port");
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(serverHostname);
System.out.println ("Attemping to connect to " + IPAddress +
") via UDP port 7777");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
System.out.print("Enter Message: ");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Log.i("send","send");
System.out.println ("Sending data to " + sendData.length +
" bytes to server.");
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Waiting for return packet");
clientSocket.setSoTimeout(10000);
try {
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
InetAddress returnIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From server at: " + returnIPAddress +
":" + port);
System.out.println("Message: " + modifiedSentence);
}
catch (SocketTimeoutException ste)
{
System.out.println ("Timeout Occurred: Packet assumed lost");
}
clientSocket.close();
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
}
In UDP, unlike TCP, there is no connection established. Every UDP packet travels on it's own.
My guess is that you can send a UDP packet to server, but you do not receive the return packet. The reason for this is NAT which is used on all home routers and cellular networks. NAT prevents delivery of inbound (internet to device) packets.
To test this assumption, try this with device and server on the same local network.
I am currently sending out a DatagramPacket on a DatagramSocket and I receive just fine.. the problem is that I am receiving the packet I sent out. If I call the receive twice then it times out. Is there a way to ignore the first packet and receive the second.
Here is my code..
socket = new DatagramSocket(8001);
socket.setBroadcast(true);
socket.setReuseAddress(false);
DatagramPacket packet = new DatagramPacket(databytes, 7,
getBroadcastAddress(), 8001);
socket.send(packet);
String localAddress = socket.getLocalAddress().toString();
byte[] buf = new byte[1024];
DatagramPacket receivepacket = new DatagramPacket(buf, buf.length);
socket.setSoTimeout(5000);
String temp = "";
String delims = "[/]";
while(true)
{
try{
socket.receive(receivepacket);
temp = receivepacket.getAddress().toString();
temp = temp.split(delims)[0];
if(temp != localAddress)
{
}else
{
m_IPAddress = temp;
break;
}
}catch (SocketException e){
} catch (IOException e){
String temp1 = e.toString();
}
}
Check to see if the address is bound to one of your interfaces.