Client socket not connecting to server socket - java

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.

Related

In which situation can I use getPort() in a DatagramSocket?

I'm using DatagramSockets to build a application and I stacked in a point of the code that I should identify which port my socket was bound. So in this part of my code:
dnsConnection = new DatagramSocket();
byte[] date = "\nSend me a available server IP!".getBytes();
pkg = new DatagramPacket(date, date.length, addr, port);
status.append("\nTrying to send the message to: " + addr.getHostAddress());
dnsConnection.send(pkg);
localPort = dnsConnection.getPort();
status.append("\nRequest has been sent to: " + addr.getHostAddress());
status.append("\nthrough the port: " + localPort);
As you can see, I'm trying to get the port in which my socket was bound using the method getPort(). Reading the API, we have this statement:
public int getPort()
Returns the port number to which this socket is connected. Returns -1 if the socket is not connected.
In this sense I continue to search an alternative and I found the method getLocalPort() and in the API:
public int getLocalPort()
Returns the port number on the local host to which this socket is bound.
Then using getLocalPort() I could have gotten the port in which my socket is bind, and I understood that getPort() is probably to get the port that the socket is connected, i.e., the port of the host in which I want to send information. After all this, grew up a question on my head:
As UDP is conectionless, in which moment can I use getPort() to recovery the port in which my socket is connected?
Maybe I understood wrong and getPort() is not related with the remote host, if I'm wrong please clarify-me.
That is.
Thanks.
Pablo
When you call dnsConnection.send(pkg), the DatagramPacket pkg includes information of the IP address of the remote host, and the port number on the remote host. When you later call dnsConnection.getPort(), it just returns the remote port number of the last sent packet, which is local information.

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!

Socket: could not connect to server or specific port

I am trying to connect server by port and Host Name.
I find one program but when i am trying to run it will show following Exception
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sample.Echoclient2.main(Echoclient2.java:31)
Couldn't get I/O for the connection to: 127.0.0.1
Java Result: 1
Here is my code which i use.
public class Echoclient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 10008);
System.out.println("server name"+Inet4Address.getByName(serverHostname));
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
System.out.println("Connection accepted " +
echoSocket.getInetAddress() + ":" +
echoSocket.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
// end loop
if (userInput.equals("Bye."))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
What i need:
1. I need to send some message to server and want response from server. Suppose i send "I am user of stackoverflow" then server should give any response like return same String or convert in uppercase or something else.
Some Questions:
1. I write client Java File but whether i need to write server java file.
2. Can we send request by using ip and port.
3. Can we use host name.
4. Any echo server name? i need to send message to this server want to know response.
5. I try both server,java and client.java then i got result? is this solution for me.
1. I write client Java File but whether i need to write server java file.
Yes, you either need to write your own server (if the server should fulfill some unique requirements) or connect to an existing one. The message "connection refused" indicates that no server is running at the port you are trying to connect to.
2. Can we send request by using ip and port.
Yes.
3. Can we use host name.
Yes. You need either IP or hostname, and the port.
4. Any echo server name? i need to send message to this server want to know response.
You can setup an echo server on your machine so that you can first focus on coding your client. There is a Standard Echo server defined at port 7. Setup depends on your operating system environment - On Ubuntu Linux, I had to install the xinetd package and enable the echo server in /etc/xinetd.d/echo. Then, you can verify if the server is running by using the telnet program:
andreas#ubuntu:~$ telnet localhost 7
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
Hello
Using telnet to connect to any port is also a common technique to verify if a server is running and reachable. With the example from your question, you could check with telnet 127.0.0.1 10008 whether a server is running on the port you specified - you will get the same connetion refused as from your Java program if no server is available.
5. I try both server,java and client.java then i got result? is this solution for me.
Not sure which server and client you are referring to.
Some additional references:
All about sockets (also includes "Writing a Client/Server pair")
Enabling desired xinetd protocols
Java Tutorial: Echo client in Java
You have to run your server program also in local host. You are getting this exception because of 10008 port not ruining on your machine.
Some Question:
I write client Java File but whether i need to write server java file.
either you can write a server program or you can connect to a remote server. In that
case you should have both ip and running port in remote server.
Can we send request by using ip and port.
Yes You required both to send a message.
Can we use host name.
If you machine can resolve your host name you can do it. Otherwice you can use ip address
Any echo server name? i need to send message to this server want to know response.
I have no idea about this , need to search on web.
I try both server,java and client.java then i got result? is this solution for me.
Yes.

Why my chat application that does not work behind a router?

I developed a chat application Java/Socket(TCP), it works perfectly on my local network,however when i put it behind a router it does not work...
I have already tested the open ports on my router at:
http://www.yougetsignal.com/tools/open-ports/
the result is as follows
80 (HTTP)is open
21 (FTP)is open
22 (SSH)22 is open
23 (TELNET)is open
25 (SMTP)25 is open
.
.
.
I started my server with this list of ports(java -jar server.jar 23) :
int port=Integer.parseInt(args[0]);
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(port);
System.out.println("server started at " + port);
Socket clientSocket = null ;
// repeatedly wait for connections, and process
while (true) {
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.Println("error");
}
System.err.println("new client connected!");
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
String s;
while ((s = in.readLine()) != null) {
out.println("from server: "+s);
}
// colse all
out.close();
in.close();
clientSocket.close();
then Then with a simple client I tried to connect => anything received....
where does the problem? so how Skype,Msn and others chat application works fine?
there is a solution to do that ?
PS:I put a simple code(echo server) that represents my real server so you understand my code quickly :).
My regards .
This is just a guess, did you go into your router's configuration utility and set it up to proxy (usually called port forwarding) telnet requests to the client? Your router may be listening on 23, but unless you're running the chat client on the router's firmware, I doubt it knows what to do with that traffic. Maybe I misunderstood your question though.
Just having a server running behind a router is not enough for an outside client to establish a connection. Whatever port the server is listening on, the router needs to have a Port Forwarding rule configured on it that forwards inbound traffic for that port to the machine the server is running on. The client then needs to connect to the port on the router's public IP so the router can then forward that traffic to the server.

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