Reputation: 3457
I have been struggling with this for a while now. What I'm simply trying to do, is to create a socket connection between my android app and my java program on PC.
I have both tried UDP and TCP sockets and different kinds of IP's and port numbers.
So, how can I achieve this?
Here is my (current code) with a (attempted) TCP connection:
Code snip from the server side (PC java program):
try {
DatagramSocket socket = new DatagramSocket(4466);
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And the relevant snip from my android app (client):
try {
InetAddress host = InetAddress.getByName("192.168.1.255");
DatagramSocket socket = new DatagramSocket (null);
byte[] buffer = new byte[2048];
buffer = "hej hej".getBytes();
DatagramPacket packet=new DatagramPacket (buffer, buffer.length, host, 4466);
socket.send(packet);
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
The IP address: 192.168.1.255 is supposed to be some kind of broadcast IP. But I have also tried different IP's like the IP for my PC (hard-coded in the android app), the 255.255.255.0, localhost and so on.
I would really appreciate it if anyone could help me out!
Upvotes: 4
Views: 8018
Reputation: 73528
You need the public address of your computer (search for something like what's my IP) and make sure there's no firewall blocking the port. The 192.168.***.* address is not public (it's a LAN address), and the emulator (or an actual phone) won't able to see it.
Upvotes: 0
Reputation: 1917
I just created simple demo in Android and Desktop application which is connected via Socket Connection and its like a Chat Application. Might be that will help you a lot. Please check below link for more clarification.
Android Client Connected with Socket
Upvotes: 5