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.
Related
I'm trying to create a local server with Wi-Fi P2P between an Android phone and a Raspberry Pi, with the Android as the host. I have been able to successfully establish a P2P connection using wpa_cli on the Pi, but now I am trying to use a C client socket to connect to the phone and transfer data. However, the line Log.d("Socket waiting", serverSocket.getLocalSocketAddress().toString()); spits out D/Socket waiting: ::/:::8888. It doesn't seem to have an address at all, so how am I supposed to connect to it?
As indicated by my comment, my research told me that the correct IP should be 192.168.49.1. If the IP were any different, that would be okay, because I can just send a BLE packet to the phone, telling it the IP. My issue is that the IP is entirely blank.
My code is as follows, for a thread that waits on a connection:
public static class DataTransfer extends Thread {
#Override
public void run() {
Log.d("DataTransfer", "Start");
ServerSocket serverSocket = null;
try {
/**
* Create a server socket and wait for client connections. This
* call blocks until a connection is accepted from a client
*/
// Expects a connection at 192.168.49.1:8888
serverSocket = new ServerSocket(8888);
//serverSocket.setReuseAddress(true);
//serverSocket.toString()
Log.d("Socket waiting", serverSocket.getLocalSocketAddress().toString());
Socket client = serverSocket.accept();
InputStream inputstream = client.getInputStream();
Log.d("InputStream Available", String.valueOf(inputstream.available()));
serverSocket.close();
}
catch (IOException e) {
Log.e("Receive Error", e.getMessage());
if(serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
Log.e("Failed to close socket", ex.getMessage());
}
}
return;
}
}
}
And here is the output of ip a on the Pi, once it is connected via Wi-Fi P2P
11: p2p-wlan0-8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether b2:0e:07:e6:e6:55 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.23/24 brd 192.168.1.255 scope global noprefixroute p2p-wlan0-8
valid_lft forever preferred_lft forever
inet6 fe80::e79c:33f3:6e49:b6ed/64 scope link
valid_lft forever preferred_lft forever
Final edit:
My problem was seemingly unrelated. As both comments below indicate, the IP shown off is fine, it just means it accepts connections from anything. My actual issue was that I had a static IP set up on my Pi without specifying which interface the static IP was for. The client needed to be on a 192.168.49.# address, and the static IP was preventing it.
You can specify the interface the server socket is listening on by passing an address to the constructor:
serverSocket = new ServerSocket(8888, 10, InetAddress.getByName("192.168.49.1"));
Seeing :: means your server was listening for IPv6 connections on all interfaces. That is represented by the IPv6 address of all zeros which can be written as ::. But you are trying to connect to an IPv4 address, not IPv6. Most systems I've worked with are configured so that IPv4 connections can be accepted by an IPv6 server, but I guess yours isn't. The answer to this question suggests you may be able to change your system's behavior with sysctl:
sysctl net.ipv6.bindv6only=0
:: is the IPv6 default route. It indicates that you are serving requests from all interfaces.
This is the expected behavior. Is there a problem with that?
I'm trying to transfer a message between two android phones over the local network. I read sockets where a good way to do this.
(I cant use bluetooth)
(I cant use NFC either)
I have built a server and client application.
One app has a server that listens for a connection.
The other app has a client that tries to connect when a button is pressed.
Both the manifest files contain the correct permissions. (with the html tags)
uses-permission android:name="android.permission.INTERNET" /
uses-permission >android:name="android.permission.ACCESS_NETWORK_STATE"/
I put the server online first:
ServerSocket myServerSocket = new ServerSocket(27024);
System.out.println("Server is waiting for incoming connection on host=" + InetAddress.getLocalHost().getCanonicalHostName() + ", port=" + myServerSocket.getLocalPort());
Socket socket = myServerSocket.accept();
Then try and connect with the client.
String host = "localhost";
int port = 27024;
try{
System.out.println("Client attempting to connect to server at host: " + host + ", port: " + port);
Socket socket = new Socket(host, port);
//This below line never gets called :(
System.out.println("Client socked created! Now trying to send data to server");
}
In my console:
Client attempting to connect to server at host: localhost, port: 27024
The "Client socked created!" line never gets output.
Both hosts are set to "localhost" and the port number is the same.
I've tried various ports, but nothing happens.
String host = "localhost";
int port = 27024;
You realize that your client needs to be given the IP address of the server, right?
Note you will most likely not be able to, or ever should, bind an app on a non WiFi interface.
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.
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.
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!