Hay Guys, I'm new to Android but heres what i want to do.
I want to beable to open a connect to a server using a given IP and PORT, then send commands to the server and get data back.
Any ideas what i need to google to help on this? I know how to do it in PHP (using fputs, fgets, and fsockopen).
any help would be brill.
Thanks
Use the java.net classes. Below is a simple example using DatagramSockets:
String cmd("my command");
try {
InetSocketAddress address = new InetSocketAddress("10.1.1.1", 12350);
DatagramPacket request = new DatagramPacket(cmd.getBytes(), cmd.length(), address);
DatagramSocket socket = new DatagramSocket();
socket.send(request);
} catch (SocketException e) {
...
}
} catch (IOException e) {
...
}
}
Other Java samples can be found here:
Related
I am trying to get some experience with Java network programming. So I made a simple text based game. This is how it looks on serverside:
try {
socket = new ServerSocket(PORT);
while(true) {
new ConnectedPlayer(socket.accept()).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And this is the client:
System.setProperty("java.net.preferIPv6Addresses","true");
try {
InetAddress ad = InetAddress.getByName("2a02:8070:b84:6b00:a1d1:30d7:346b:7c14");
socket = new Socket(ad, 9001);
output = socket.getOutputStream();
out = new PrintWriter(output);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The address above is the Ipv6 address of the machine running
the server, I got this one by a website which detects my IP addresses,
it is different from what I get when I use ipconfig though, tried it with both.
When I tested both on the same machine with localhost, it worked.
However, now I wanted to try it on two different machines, one in a different network. Problem is, my internet provider apparently restricts me to something called "dual stack lite" which means my Server could only be reached over Ipv6 if I understand it correctly. But then, no port forwarding is needed there. When I test it now, it won't connect and gives a timeout after some time. I disabled firewalls on both machines.
I'm working on a small project for learning purposes , consisting of two instances of clients and a server instance .
The server and one of the clients are running on my PC whose code is written in Java , while the 2nd client runs on android .
The server is listening on a given port. When the Java client sends a packet to the server , it retains the IP / port to send in response to a future packet received from the android terminal , and vice versa.
Communications between each client and server working properly. But when communicating between clients ( assuming each acquired the ip / port on the other , as a response from the server) nothing comes to android terminal.
In both instances of the client, the socket is created as :
DatagramSocket socket = new DatagramSocket ();
Then contact the server only once , to store my address data :
Socket.Send ( sendPacket ) ;
( SendPacket is instantiated with fixed data server)
And then instantiate the listen method , passing as parameter one datagram packet containing only the number of bytes to receive.
socket.receive (packet );
Implementing this method in an infinite loop , I've only managed to receive packets from the server ( the answers ) and not the other client application.
The permissions in the manifest I use are:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
I appreciate any tip . Thank you very much !
I have implemented two socket one for send and another for receiving and is working for me whit some modifications attending to my needs. I am assuming you are forgetting the port ... or something... put a log of your error or more code to help you...
Below is the code working for me
int port =1515;
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
//////send socket
int eport = 1616;
InetAddress eip = null;
try {
eip = InetAddress.getByName("192.168.1.1"); ////SERVER IP ADDRESS ---- Server comunication is working so I assume you have it
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramSocket esocket = null;
try {
esocket = new DatagramSocket(eport);
} catch (SocketException e) {
e.printStackTrace();
}
//////Start receive
while(true)
{
byte[] message = new byte[60*1024];
DatagramPacket recv_packet = new DatagramPacket(message, message.length);
try {
socket.receive(recv_packet);
} catch (IOException e) {
e.printStackTrace();
}
///Do something whit recv_packet
}
I am learning currently about client server communication using Java through sockets.
First of all I retrieve my own machine's IP Address using following code.
InetAddress ownIP=InetAddress.getLocalHost();
//the result being 192.168.56.1
Now I write the simple client server application using the above mentioned address as follow
public class SimpleClientServer {
public static void main(String[] args)
{
//sending "Hello World" to the server
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
clientSocket = new Socket("192.168.56.1", 16000);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out.println("Hello World");
out.close();
in.close();
clientSocket.close();
}
catch(IOException e)
{
System.err.println("Error occured " + e);
}
}
}
The result hower reads a follow.
Error occured java.net.ConnectException: Connection refused: connect
What is the reason for this. Is it just the wrong host address?
From the code you have given you seem to suggest that there is currently nothing listening on port 16000 for the socket to connect to.
If this is the case you need to implement something like
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(16000);
}
catch (IOException e) {
System.err.println("Could not listen on port: 16000.");
System.exit(1);
}
More information can be found in the Java online documentation and a full example is included.
With sockets, no matter what language you're using, you either initiate a connection with socket_connect or you listen and accept with socket_listen and socket_accept. Your socket_connect call is trying to connect to an ip address that doesn't seem to be listening to anything.
i want to program a server/client app in android.
i have one server class on my pc and client on my android phone.
all permissions are ok.
Here is client:
try {
mysocket = new Socket("My PC IP Address", 4444);
} catch (UnknownHostException e) {...
} catch (IOException e) {...
}
here is server:
try {
myServerSocket = new ServerSocket(4444);
} catch (IOException e) {...
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connection Established.");
} catch (IOException e) {
}
I uses "Connectify" program on my pc to have an (virtual)access point such that my phone connect to that.
But when I try to connect to server in my android app, it hangs and then throws Timed-out exception.
This code doesn't look bad.
Are you certain Connectify is working well?
You shoud try running both the server and the client you have built on your PC, using two different processes (as an example the server as a standalone and the client in the Android Emulator).
If it works properly from localhost to localhost:4444, the the connection is the cause of the problem, not your code. And otherwise, you will easily find the bug in your code.
I have an app in android in which I created an android client and a Java sever.
But I'm confronting the following issue: my client (the android part) connects to the local machine on port 6000 using the android loopback address.
My server (in Java) listens on local machine at the port 6000 - but what is the IP I have to use to get the socket that accepts the clients?
InetSocketAddress serverAddr = new InetSocketAddress(SERVERIP,serverPort);
serverSocket = new ServerSocket();
serverSocket.bind(serverAddr);
So what is the SERVERIP I have to use?
UPDATE:My client runns on an emulator!!!!!
EDIT:
public class ClientThread implements Runnable {
Object syncToken;
public ClientThread(Object syncToken) {
this.syncToken = syncToken;
}
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, 50458);
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err
.println("Couldn't get I/O for the connection to host");
}
try {
out = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
while (true) {
synchronized (syncToken) {
try {
syncToken.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
And here is: private String serverIpAddress = "10.0.2.2";!!!!!
From http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking: if you want to communicate from within the emulator to the local host, use IP 127.0.0.1 on the local host and use IP 10.0.2.2 in Android. This should let you communicate between the Android client and the local host server.
You want to run the server part on the Android? I guess not, and in such case using loopback address is not really going to work, as loopback interface on the Android system loops back to the Android machine itself, it is not routed to the outside.
For the serverAddr, use the #InetSocketAddress(int port) constructor, it specifies the wildcard address and a specific port, meaning it listens on all the interfaces of the machine.
Edit: For best results, on the android device use the DNS name of the server to connect to it.