Sending data from Android device to a Computer using UDP - java

I wish to send live images captured by the android device to a computer running UDP server. I wish to start this project using a simple data like String. However I am not able to send a String from an Android device to a Computer running UDP server in Netbeans.
Android Code - Client: (This code resides in the on button click listener)
try {
InetAddress address = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
sendData = "Hello Server".getBytes();
DatagramSocket datagramSocket = new DatagramSocket();
DatagramPacket datagramPacket = new DatagramPacket(sendData, sendData.length, address, 2222);
Log.i("","Client Created");
datagramSocket.send(datagramPacket);
Log.i("", "Datagaram Packet Sent");
} catch (Exception ex) {
}
Java Code on PC - Server:
public class Server {
public static void main(String[] args) {
try {
byte[] receiveData = new byte[1024];
DatagramSocket datagramSocket = new DatagramSocket(2222);
DatagramPacket datagramPacket = new DatagramPacket(receiveData, receiveData.length);
datagramSocket.receive(datagramPacket);
System.out.println("Datagram Packet Received");
String message = new String(datagramPacket.getData());
System.out.println(message);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

Related

Why does server process multiple clients at the same time when it's not multithreaded?

So in my code below i have a singlethreaded server and a multithreaded client. The reason for this is because i want the client to send packets and receive packets simultaneously. However when i start the server and run multiple clients the server can process multiple clients simultaneously even tough the server is not multithreaded? Can you explain this?
Server:
public class server {
public static void main(String[] args) throws IOException{
new server();
}
//declare the UDP server socket
DatagramSocket datagramSocket;
int port = 3741;
public server() throws IOException {
//create UDP server with a specific port number
datagramSocket = new DatagramSocket(port);
System.out.println("[UDP server] Datagram socket started on port " + port);
//prepare the packet structure for received packets
int dataLength = 100; //must be large enough so some part of packet doesn't get lost
byte[] receiveData = new byte[dataLength];
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
while(true) {
datagramSocket.receive(packet);
System.out.println("client connected");
InetAddress inetAddress = packet.getAddress();
int clientPort = packet.getPort();
byte[] data = packet.getData();
//send response back to the client host
byte[] sendData = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(data, data.length, inetAddress, clientPort);
datagramSocket.send(datagramPacket); //sending data from server to client
}
}
}
Client:
public class client {
public static void main(String[] args) throws Exception {
new client();
}
public client() throws Exception{
DatagramSocket socket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");
String message = "hello from client";
DatagramPacket packetSend = new DatagramPacket(message.getBytes(), message.getBytes().length, ip, 3741);
Thread th = new Thread(new Runnable() {
#Override
public void run() {
for(int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.send(packetSend);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
th.start();
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//this part can't be in a thread because the loop above us will finish first before this starts
//we can put this code before the loop and start a thread this would also work
while(true) {
try {
socket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String data = new String(packet.getData()).trim();
System.out.println(data);
}
}
}
You think "the server can process multiple clients simultaneously even tough the server is not multithreaded" cause your brain cheat you. Acutually they are processing one by one in a reliatively fast speed. It's easy to see if you use wireshark or tcpdump to capture the server side packets. You will find the interesing truth.

Does a UDP connection require a server/client?

I want to send out a UDP packet/message out to another device on the same ethernet connection, but I'm not sure where a server/client relationship would be here.
The receiving message is configured to automatically send a response back upon receiving a message, so both devices would just be communicating to each other...
Am I missing something?
I'm confused because the code I used to send a message from a client to a server has parameters "server ip" and "server port" so I'm not sure if I can 1) just replace the parameters and use the same code and 2) if it's possible, what to put in those parameters, the initial device's port # and ip? Or the second device's?
Thanks!
The code snippet:
new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress SERVERIP = InetAddress.getByName(SERVER_IP);
DatagramSocket socket = new DatagramSocket();
socket.setBroadcast(true);
byte[] msg = message.getBytes();
DatagramPacket packet = new DatagramPacket(msg, message.length(),
SERVERIP, SERVERPORT);
socket.send(packet);
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
I'm not entirely sure if the question you want answered is how to respond to the device that sent the message from the device that received the message.
If this is the case then the following code is a basic example of how you could respond to the initial sender device by getting the address and port from the packet that was received over the socket.
// Receive and respond thread.
new Thread(new Runnable() {
#Override
public void run() {
try {
// Receive
DatagramSocket socket = new DatagramSocket(4445);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// Respond
// Get sender's/return address from the packet that was received.
InetAddress address = packet.getAddress();
// Get sender's/return port from the packet that was received.
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
I would also recommend reading the following documentation regarding writing a datagram server and client.

Java UDP respond to broadcast request

At work we are developing an android app that communicates with set top boxes(STB).
It all works fine but I'm trying to create a "mock" STB that the app can connect to so I can control the responses for testing.
I have no access to the code in the STB to know how they set up the sockets but I do have a simplified version of the client code used by the app.
Here's the client code:
public class UDPClient {
public static void main(String[] args) throws SocketException, UnknownHostException {
DatagramSocket c = new DatagramSocket(12345);
c.setBroadcast(true);
c.setSoTimeout(20000);
String msearchData = "DATA";
byte[] sendData = mSearchData.getBytes();
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
c.send(sendPacket);
System.out.println("Request packet sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// wait for reply
byte[] recBuf = new byte[15000];
DatagramPacket receivePacket = new DatagramPacket(recBuf, recBuf.length);
try {
c.receive(receivePacket);
System.out.println("PACKET RECEIVED!");
System.out.println(new String(receivePacket.getData()));
} catch (IOException e) {
e.printStackTrace();
}
c.close();
}
}
When I run this code on my development laptop (and I'm on a wireless network with that STB) the STB responds.
However, I have another laptop setup to pretend to be another STB on the same network(mock STB).
The "mock" STB simply refuses to pick up the broadcasts requests and I'm stuck.
Here's some code I use to act as the mock STB. I've tried various combinations of ports but nothing works.
public class MockBox {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
socket.setBroadcast(true);
while (true) {
System.out.println(">>>Ready to receive broadcast packets!");
byte[] recvBuf = new byte[15000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(packet); // blocks
// Packet received
System.out.println(">>>Packet received from " + packet.getAddress().getHostAddress());
System.out.println(">>>Packet data: " + new String(packet.getData()));
socket.close();
}
}
}
Any help appreciated!
Disable the software firewall.
Use MulticastSocket instead of DatagramSocket. (Note: The address you specified above is a multicast address.)
Use TTL of at least 1. If that doesn't work, use 2. Repeat, but don't go above say 4 or 5 on a LAN, because at that point, you're already past reasonable. (Zero won't leave the machine. Using a value too high may cause the packet to be discarded somewhere along the route.)

Sending and receiving UDP packets?

I have made a program to send an UDP packets from a client to a server.
Here is the transmitter code:
import java.io.IOException;
import java.net.*;
public class JavaApplication9 {
public static void main(String[] args) throws UnknownHostException, SocketException, IOException {
// TODO code application logic here
byte[] buffer = {10,23,12,31,43,32,24};
byte [] IP = {-64,-88,1,106};
InetAddress address = InetAddress.getByAddress(IP);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, address, 57
);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packet);
System.out.println(InetAddress.getLocalHost().getHostAddress());
}
}
The receiver code function is this:
public void run() {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
byte[] sendData = new byte[8];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
String sendString = "polo";
sendData = sendString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
I have used the Wireshark program. The UDP packet is received in the Wireshark program at the receiver but the Java program wouldn't recognize it, the program just keeps listening to the port and nothing happens?
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging, try listening on port > 1024 (e.g. 5000 or 9000). Ports < 1024 are normally used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check to prevent such a situation.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}

socket programming with implement & interface

I tried this tutorial with socket programming. BUT, it is unable to send message to server when doing socket programming with implement & interface. Do you think that i can do socket programming with implement & interface?? There is also no "hello" debug message.
private class OnReadyListener implements MyCustomDialog.ReadyListener
{
#Override
public void ready(String name)
{
try
{
DatagramSocket clientSocket = new DatagramSocket();
String serverHostname = new String("192.168.1.12");
InetAddress IPAddress = InetAddress.getByName(serverHostname);
byte[] sendData = new byte[1024];
String sentence = "hello";
Log.d(TAG, "OnReadyListener ready" + " " + sentence );
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
clientSocket.close();
}
catch (UnknownHostException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
here is code implemented in different form than yours, but it is pure socket programming and works well.
http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

Categories

Resources