Getting string from one android device and sending to other devices - java

I try to develop an android app and I got stuck on this problem.
I want to send two string values(longitude, latitude) from one android device to other android devices that have the same app. From researching online, my understanding is that the android devices sends the two strings to a server and then I can use google gcm to send those strings to other devices(I think). Maybe the server can run java and I can write some program to do something with the data it receives later.
I have successfully obtained the location data from the android device, but got stuck on sending this location from android phone to a server on my computer. My professor told me that I can make my computer a server. Before connecting android and my mac, I tried connecting two computers. I successfully connected my imac and macbook using Socket&SocketServer examples found at the bottom of http://www.tutorialspoint.com/java/java_networking.htm. It took a long time because I didn't know I had to remove the firewall.
So I found another example to connect an android to a computer using Socket at http://lakjeewa.blogspot.ca/2012/03/simple-client-server-application-for.html and tried it. Although, two computers could be connected, android won't connect to my computer. I think the problem is in the code
client = new Socket(serverName, port);
I tried many things for serverName such as the computer's ip address that start with 192.168, "localhost", 10.0.2.2, http:/myIpAdressFoundByGoogling, "myComputerName.local" but none worked. What's the problem here? The android device does not have a sim card and it is connected to the same wifi as the computer. I should have XAAMPP? (I just found about this last night) and learn php first? I am completely lost what to do with server.
I ended up here because I was thinking I can test and develop the app using a computer as a server and when I finish developing, I can get a server(like amazon web services, I am not sure yet) and replace the server location in the code, and copy and paste the server java code. Can I do this? maybe Google App Engine is a viable solution for my problem?
The client code is...
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message;
private int port = 5555;
private String serverName = "192.168.?????"; I think this is where the problem is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = textField.getText().toString();
textField.setText("");
try {
// connect with server
client = new Socket(serverName, port);
printwriter = new PrintWriter(client.getOutputStream(),
true);
printwriter.write(message);
printwriter.flush();
printwriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
The server code is...
public class main {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) {
int port = 5555;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println("could not listen on port: " + port);
e.printStackTrace();
}
System.out.println("server started listening to the port " + port);
while (true) {
try {
// accept the client connection
clientSocket =serverSocket.accept();
System.out.println("someone connected to the server");
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
//get the client meesage
bufferedReader = new BufferedReader(inputStreamReader);
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException e) {
System.out.println("problem in reading the message");
e.printStackTrace();
}
}
}

You are probably unable to connect your android device to your computer wither because there is some configuration problem or something is wrong in the code at one end. I have previously successfully sent messages from an android device to a "server" that ran on my laptop, I did this with the Socket and ServerSocket technique very similar to the example you linked to. So this is more than possible. There is no need to install additional software on either side (Java run-time is enough).
If both the computer and the android device are connected on the same wifi network you should use the internal LAN address. If you are running this on the android emulator and you want to connect to the host computer (the computer that runs the emulator) you can use 10.0.2.2 or just the computers address (this works also). What port are you using? Is this port open on your router settings, firewalls, etc.?
You do not have to learn PHP or App Engine to do what you are trying to do. You can, and these will also allow you to do this (I have no experience with App Engine but I am pretty sure it can). As for the PHP you will need to install XAAMPP on your machine to be able to use this as a server.
Another question is: If you plan to actually put this on a server you should check what kind of server you will have/need. A simple hosting package will most likely not allow you to run your own java code there but will probably allow you to run PHP scripts, for example.
If you post the networking code of both the client and the server, you will be able to get more accurate feedback than just my general and top-level answer.

I am taking an Android development class at the moment as well. I think you should look into Parse, it is a free service that provides all the backend server stuff for you, for free. We have been using it in out app. Once you get the hang of how the callbacks work it's very easy to use. Otherwise I would recommend looking into some kind of web framework like ruby on rails, and write your backend in that. You can deploy all that onto heroku and then assess your backend with android async talker.

Have you tried to connect to your server via a webservice and then consume that webservice in your application? I've successfully connected my device to my laptop doing this.
Take a look at this guys tutorial:
http://android.programmerguru.com/android-webservice-example/
I believe this is the best practice when communicating device to server.

Related

How to make a local multiplayer java game runs online?

I've developed a decent amount of multiplayer games lately in java (board/turn based games running on a tcp connection with data in/out streams) but they only work locally, I want to go a step further and make them run online, what do I need to change to make it work?
It seems like there are many ways to accomplish that yet i don't know where to start, as I don't know much about networking.
Besides that I don't have a real server, I'm only using my home router and my pc.
So here is what I've tried so far:
I enabled port forwarding in my router and I think it works (I used a port forwarding checking tool online)
I created a dynamic DNS for my public ip using noip.com
So the server side should be fine at least, my problem is with the client side, the client's socket won't connect to my public ip, when I searched for a solution I concluded that the client shouldn't be in the same LAN where the server is, so I used a mobile hotspot as a second network and tried again, but got the same results. (connection refused exception)
is it because of the mobile hotspot (should I use another router) ?
or is it just some coding tweaks ?
This is a minimal server class example
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(50895);
Socket cs = ss.accept();
DataOutputStream out = new DataOutputStream(cs.getOutputStream());
DataInputStream in = new DataInputStream(cs.getInputStream());
out.writeInt(123456);
} catch (IOException e) {
e.printStackTrace();
}
}
And this a minimal client class example
public static void main(String[] args) {
try {
String ip = Inet4Address.getByName("my Dynamic IP address").getCanonicalHostName();
System.out.println(ip);
InetSocketAddress sa = new InetSocketAddress(ip, 50895);
Socket cs = new Socket();
cs.connect(sa);
DataOutputStream out = new DataOutputStream(cs.getOutputStream());
DataInputStream in = new DataInputStream(cs.getInputStream());
System.out.println("received : " + in.readInt());
} catch (IOException e) {
e.printStackTrace();
}
}
The method that i've tried always gives me a connection refused exception, so any solution would be appreciated.
I found a software solution to the problem through virtual lan (using LogMeIn Hamachi) which is basicly used for creating game servers, you just need to create an account and a network so your friends can join it, after that everything should be fine and runs as if it's locally hosted.
You can download the software through here but there are many alternatives to choose from, that one gives you up to 5 people on the network for free, it's not the best, but still a free solution.
I still want more of a java solution to this problem that doesn't require a third-party software.

Socket connection won't work between smartphone and computer

I have a C# WPF application that uses TCPListener to start a Server in my computer, and an android app that works as a client. It works perfectly when I start the server and emulate the app in my computer, but most of the time it just doesn't work when I use my smartphone to connect to my computer, it only works some times after I restarted my router DHCP and my smartphone.
If you need, here's the connection code
Server:
private static IPAddress ipAd;
private static TcpListener server;
private static TcpClient client;
public static void start() {
//Already tried with both
ipAd = IPAddress.Parse(TCPServer.GetLocalIPAddress());
//ipAd = IPAddress.Parse("127.0.0.1");
server = new TcpListener(ipAd, 1209);
client = default(TcpClient);
try {
server.Start();
Console.WriteLine("Server started");
} catch {
Console.WriteLine("Failed to start server");
}
Client:
Socket socket = null;
String response = new String();
try{
//connect This ipAddress is the same in my desktop
InetAddress ipAd = InetAddress.getByName(ipAddress);
socket = new Socket(ipAd, 1209);
//send
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.write(message.getBytes());
}
...
Thanks for your time, I've should had dedicated more to my Computer Networks class...
Should I redirect some specific port? Have some specific configurations in my router/firewall? I think I'm missing something
This would work when your devices located in the same network in terms of IP routing. However even part of the most simple SOHO grade WiFi routers/AP enable so called device isolation, denying access from wifi devices in the network access between them or to clients, connected with ethernet.
To make this setup work reliably you need to ensure the following:
Use external address of your router in the mobile application. (You can discover it browsing http://whatismyip.org from the server)
Setup port forwarding in your router for particular port to particular IP in your internal network.
As for privided source code, you'd rather use 0.0.0.0 as bind address in the server app, because default .NET implementation will select first available IP address and it may be not the one you're using for connection in the mobile app or not related to the same network. This approach may have security and convenience (coexistence) problems in case of complex networking setup, but will work good for most of the cases.

Java DatagramChannel - Cannot ping port from external network

I am writing a server which uses a DatagramChannel (non-blocking) to send/receive data. It works flawlessly on my local network, but if I try to connect to it using the client application from a different network (i.e. over the internet), I cannot reach it.
Whilst running, if I use http://ping.eu/port-chk/ to check the port, it says it's closed. I have forwarded the appropriate ports and adjusted firewalls to appropriate levels.
My code is as follows:
public void runServer(int portNo)
{
try
{
serverChannel = DatagramChannel.open();
ipAddress = InetAddress.getLocalHost();
//ipAddress = InetAddress.getByName(getPublicIP());
//serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); //Added in to try to fix
serverChannel.socket().bind(new InetSocketAddress(portNo));
serverChannel.configureBlocking(false);
serverChannel.socket().setReceiveBufferSize(receiveBufferSize);
serverChannel.socket().setSendBufferSize(sendBufferSize);
//serverChannel.connect(new InetSocketAddress(ipAddress,portNo)); //Added in to try to fix
serverRunning = true;
}
catch(IOException e)
{
e.printStackTrace();
}
}
The parts which are commented out have had no effect. The ipAddress variable in the example will fetch the local IP, where as the commented-out version will get the public IP of the computer.
If you could help me find out why I cannot connect to this port over the internet, I would be very grateful.
You haven't forwarded the ports correctly. Nothing to do with the code.
As #EJP has suggested, there doesn't seem to be anything wrong with my code. I have since hosted this server application using Amazon EC2, and it has worked flawlessly.
There is an issue with the firmware of my router which is preventing port forwarding.

How to run a simple socket server that allows incoming connections?

I am trying to build a very simple socket server in JAVA that my Flash application can listen to. I am using this tutorial. Everything seems to be working - the JAVA code is compiled and the server is running.
My question is: how can external applications send messages to this server using just an IP address and a port number? My goal is that flash can listen to socket messages sent by an external application.
The Java code:
import java.io.*;
import java.net.*;
class SimpleServer {
private static SimpleServer server;
ServerSocket socket;
Socket incoming;
BufferedReader readerIn;
PrintStream printOut;
public static void main(String[] args) {
int port = 8080;
try {
port = Integer.parseInt(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
// Catch exception and keep going.
}
server = new SimpleServer(port);
}
private SimpleServer(int port) {
System.out.println(">> Starting SimpleServer");
try {
socket = new ServerSocket(port);
incoming = socket.accept();
readerIn = new BufferedReader(
new InputStreamReader(
incoming.getInputStream()));
printOut = new PrintStream(incoming.getOutputStream());
printOut.println("Enter EXIT to exit.\r");
out("Enter EXIT to exit.\r");
boolean done = false;
while (!done) {
String str = readerIn.readLine();
if (str == null) {
done = true;
} else {
out("Echo: " + str + "\r");
if(str.trim().equals("EXIT"))
done = true;
}
incoming.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
private void out(String str) {
printOut.println(str);
System.out.println(str);
}
}
Maybe I don't understand correctly your problem description, but if you create the server in Java, it listens to its port and not your Flash application. If you want your Flash application to wait for messages from other applications, it must have a server role and listen to a TCP port the same way as this Java server does.
You can connect to and test the given Java server easily by telnet program (available in all operating systems) by providing a host name or an IP address and a port as parameters:
telnet 127.0.0.1 8080
Any other application can connect in a similar way, using just a hostname/IP address and a port. For example in Java, you can create a client socket:
Socket clientSocket = new Socket("localhost", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
By not specifying an IP address for your socket, it will listen on 0.0.0.0 (all interfaces).
In fact, that will usually be your computer's IP / the server's IP.
Assuming that your application runs on your computer at home, there are three cases that cover most of the connection situations:
Connecting from the same machine:
Use 127.0.0.1:8080
Connecting from the same LAN (e.g. your brother's PC):
Use your LAN IP (e.g. 192.168.1.4:8080)
Connecting from WAN (outside your routers LAN) (internet e.g.):
Use your WAN IP.(e.g. 84.156.74.194). There are plenty websites, that tell you your WAN IP like this
You may have to setup your router, to forward the port 8080 to your PC
For simple connection tests, one could use a telnet client.
I think you are missing the point of client/server socket applications.
If you are building the socket server (with whatever programming language you chose), you will then need to connect with (a) socket client(s) to this server. After a connection is successfully established (persistent) between the client and the server, you can start what ever kind of communication you have implemented between them.
The server always acts as the passive, the client as active part in a socket server/client constellation.
I was checking the link that you are referring to. In that, the procedure to create a stand-alone server is mentioned which is the code that you have pasted as well.
According to the link, the application acts as the client and uses the XMLSocket methods to connect to this server. This application is the flash application that you are talking about. As mentioned in the link, by using the following code any flash application can connect and talk to the server:
var xmlsock:XMLSocket = new XMLSocket();
xmlsock.connect("127.0.0.1", 8080);
xmlsock.send(xmlFormattedData);
When you mention
My goal is that flash can listen to socket messages sent by an external application.
its actually the flash application that is the client and it cannot listen unless programmed to act as a server. I hope this provides some clarity!

Android device to PC's socket connection

I am facing problem to establish a socket connection from android device to PC's a specific port like 8080. I just want to create a socket which will connect to the specific port and also write some data stream on that port.
I have written some code for this purpose but the code is giving me an exception as:
TCP Error:java.net.ConnectException:/127.0.0.1:8080-connection refused
I am giving my code as below:
private static TextView txtSendStatus;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
String sentence = "TCP Test #1n";
String modifiedSentence;
try {
Socket clientSocket = new Socket("192.168.18.116", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
printScr("TCP Connected.");
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
printScr(modifiedSentence);
printScr("TCP Success !!!");
clientSocket.close();
} catch (Exception e) {
printScr("TCP Error: " + e.toString());
}
}
private void initControls()
{
txtSendStatus = (TextView)findViewById(R.id.txtSendStatus);
}
public static void printScr(String message)
{
txtSendStatus.append( "n" + message );
}
Is there anyone who can tell me the answer?
I am waiting for the right answer.
Best Regards,
gsmaker.
If you are using wifi, you need to use the IP address of your PC on the wifi network. You can find this at the command line with ifconfig (linux) or ipconfig (windows)
If you are using the usb adb connection, you can't exactly do this, but you can set up an adb port forward (see developer docs) from the PC to the phone, and have the pc connect to it's loopback interface and the port, which will be forwarded to an unprivileged port number on the phone where your application should be listening. You then have a TCP or whatever connection which you can push data over in either direction. But the PC has to be the initiator to set up the connection - adb does not support "reverse tethering" in which the phone initiates network-over-usb connections to the PC in the way that is supported for the android emulator.
Your server needs to be on the device and the client needs to be on the computer.
You'll need to have adb forward the port you want to connect to the device.
After your connection is established, you'll be able to communicate between them normally.
I wrote up a full explanation here http://qtcstation.com/2011/03/connecting-android-to-the-pc-over-usb/
First off, if you try to connect to 127.0.0.1 from your device, it's only logical you can't. Because the 127.0.0.1 is the loopback interface and always points on the device itselfs.
So if you connect to 127.0.0.1 from your PC it will connect with itself. If you call it on android it tries to connect with itself too.
And second: I think the only way you could do this is when you're using WLAN, only then you have IP based connection to the PC (correct me if I'm wrong). You can't connect to your PC using USB or Bluetooth.

Categories