I am implementing a client-server application . I am new to this . I tried following the article A Simple Java TCP Server and TCP Client
Actually i already have a client that works ( Not my code )
So i just need to write the server for it .
Also my server will be connected by only one client so i dont really see the need to support multiple clients .
As i see using netstat -a a listening server is created but the client fails to connect to it . There is no error message given out either which is suprising . Its as if the call to connect is ignored . No exceptions are seen on the client .
My Server Code ( Probably Faulty)
private static void create_request_server(int requestport) {
// TODO Auto-generated method stub
try {
ServerSocket s1 = new ServerSocket(requestport);
requestsocket = s1.accept();
// Do some stuff . But this accept never breaks.
} catch (Exception e) {
e.printStackTrace();
}
}
Correct Client
try {
fRequestSocket = new Socket("localhost", requestPort);
fRequestWriter = new PrintWriter(fRequestSocket.getOutputStream());
fRequestReader = new BufferedReader(new InputStreamReader(fRequestSocket.getInputStream()));
} catch (UnknownHostException e) {
abort(" UnknownHostException", e);
} catch (IOException e) {
abort(" IOException", e);
}
FYI
Both my client and server are on localhost
Is my server horribly incorrect ?
EDIT( Close to answer)
SO with the help of the valuable comments posted below i figured out what the problem is .
The issue is between localhost & 127.0.0.1
So i did a netstat -a and saw that a server is created as follows :
TCP [::]:56283 Sin-Host LISTENING
instead of
TCP 127.0.0.1:56283 Sin-Host LISTENING
Thus the client is unable to connect . Any ideas of how to make the server bind o 127.0.0.1
Any changes that can be made to ServerSocket s1 = new ServerSocket(requestport) ?
Sometimes there is a problem with localhost and 127.0.0.1
Try the ip in your client maybe this works.
Just to see it easier than in the comments with this constructor you maybe can configure your server:
new ServerSocket(1234,10,InetAddress.getByName("127.0.0.1"));
Have you tried checking your firewall?
Possibly your firewall is blocking the requests.
The way you set up a connection looks a lot like the way I do it. But it works fine here.
Once you have your socket, you still need to create an in and output stream to send and receive data from and to your server (lol grammar)
OutputStream writer = requestsocket.getOutputStream();
and
BufferedReader reader = new BufferedReader(new InputStreamReader(requestsocket.getInputStream());
Now whenever you want to send data to your client from your server you can do something like this:
writer.println("Data sending to client that's listening to my server");
Related
I'm running the standard Java networking example from Oracles site , and it runs a simple Knock-knock joke program. This creates teh standard sockets, which I believe are TCP connections(or am i wrong here? ) .
What's confusing me is that when I view the ports in TCPView , what is see is that there are multiple lines showing for port 4444 (the one we connect to with the Knock-Knock program). Here's a screenshot( full image here ):
Why does it show both UDP and TCP ? Shouldn't it only be TCP ?
Nothing in the sample code is using UDP on port 4444. Your TCPView also shows that it's another process (different PID) that is using the UDP port:
Also, when I run the sample code, I only see the TCP records:
My guess is that you might have another sample running with a DatagramSocket ?! You might verify that the sample code is not the one using the UDP ports, by changing it to use a different port. Try e.g. changing the port to 5555 in the KnockKnockServer:
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(5555);
} catch (IOException e) {
System.err.println("Could not listen on port: 5555.");
System.exit(1);
}
and in the KnockKnockClient:
try {
kkSocket = new Socket("localhost", 5555);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
and see if you have any UDP records on this port.
There are two different processes there. Any chance you have a stale process running the udp demo hanging around?
I am using Java to do the socket programming as below.
Client program is as below:
Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Server program is as below:
ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Socket clientSocket = null;
try {
clientSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}
Now my question is if I run more than one thread to open several sockets in one port (as the server code above), how my client program know which socket it is connecting to?
Your client connects to the Servers port. So all clients will be having the same code
MyClient = new Socket("Machine name", <port where server is listening>);The port opened at client side is not important. The client will get a free port available in his OS.
how my client program know which socket it is connecting to?
The question doesn't make sense. It doesn't 'connect to a socket' at all, it connects to a listening port, and there is only one of those. Your server only accepts one client, so the second and subsequent threads will get an undefined behaviour ranging from a ConnectException to a ConnectionException to nothing, most probably the latter.
Your application knows it because you set it up with a specific port. There is no "auto discovery" built into TCP/IP, it's up to you to pick a server-port and make sure you set your clients up to connect to that port. Either you hard-code this into your client application or, better yet, have it in some configuration file you include with the client.
This is why you have a bunch of "known ports", like http is port 80. This means that a browser will always connect to port 80 on a web-server, unless you explicitly indicate another port in the URL.
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.
I need to build an application which can receive data from over a network and use this data to do some unrelevant things with.
Here's a piece of code to make clear what I'm doing.
On the server side:
static Socket client = null;
static ServerSocket ss = null;
if (ss != null) {
ss.close();
}
ss = new ServerSocket(5513);
isrunning = true;
System.out.println("Waiting for client...");
client = ss.accept();
System.out.println("Client accepted.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
And the client side:
Socket client = null;
PrintWriter out = null;
try {
client = new Socket("hostname", 5513);
out = new PrintWriter(client.getOutputStream(), true);
}
Please note that this is just a piece of the code. There are no errors in the code.
After running the server-sided piece of code, it correctly waits for the client to connect.
Now here comes the problem. As soon as I try to connect from the client side, I'm getting a "connection refused"-error.
HOWEVER, I found something on the internet whoch told me to try telnetting from the client side. For example, let the server-sided IP be 192.168.1.1. So, after using this command:
telnet 192.168.1.1 5513
I actually get a connection with the server. The command will launch an empty screen, and everything I manually type in the command line will be sent to the server-side after pressing enter (checked with debugging).
So, I can manually connect to the server-side and send some data, but my code refuses to connect.
Anyone who knows what I am doing wrong?
Is this the code you're actually using?
client = new Socket("hostname", 5513);
Try changing it to:
client = new Socket("192.168.1.1", 5513);
client = new Socket("hostname", 5513);
Hostname needs to represent the IP Address you're connecting to. If you're trying to connect to yourself, it would be "localhost"
Also, the server is not listening for the client AT ALL TIMES, there must be a while loop so the server listens and accepts connections.
while (true) {
client = ss.accept();
out = new PrintWriter(client.getOutputStream(), true);
//You should probably assign it to a seperate thread to handle stuff for this client
}
And I should explain on why you're getting that particular error. When something says that the connection is refused, it usually means that the IP Address you want to connect to knows your sending a connection and is blocking it because it was not listening for that connection. Basically, when the server closed, you stopped listening for the client, so anything that came in on that port would be blocked. Of course, the other case could be that Java was blocked on your firewall and an exception should be made for it. Although this is rarely the case if what you're trying to accomplish is over a LAN.
You're not actually using "hostname" in your Socket object in the client are you?
It should the 192.168.1.1.
Are you on Windows? and If so have you added java.exe and javaw.exe to Firewall with inbound and outbound enabled? and have you added a rule for 5513 to your Firewall?
If yes Windows but no Firewall settings, that's your answer, open up your Firewall.
I hope you can help. Im fairly new to progamming and Im playing around with java Sockets.
The problem is the code below. for some reason commSocket = new Socket(hostName, portNumber); is returning true even when it has not connected with the server (server not implemented yet!). Any ideas regarding this situation?
For hostName Im passing my local machine IP and for port a manually selected port.
public void networkConnect(String hostName, int portNumber){
try {
networkConnected = false;
netMessage = "Attempting Connection";
NetworkMessage networkMessage = new NetworkMessage(networkConnected, netMessage);
commSocket = new Socket(hostName, portNumber);
// this returns true!!
System.out.println(commSocket.isConnected());
networkConnected = true;
netMessage = "Connected: ";
System.out.println("hellooo");
} catch (UnknownHostException e){
System.out.println(e.getMessage());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
Many thanks.
EDIT: new Socket(.., ..); is blocking isnt it? i thought in that case if that was processed without exceptions then we have a true connection?
EDIT: I played around with anti virus and now it is working!
Had that exact same situation a few days ago on a corporate computer, and searched for it for hours.
Check your antivirus, some antivirus (like E*** N**32) use live TCP scanning that make a connection succeed even if nothing is listening on the target port but will reset it later when you try to read/write from the socket.
Add this to your code:
commSocket.getOutputStream().write(0);
commSocket.getInputStream().read();
If you get a SocketException now, you should really consider to change your antivirus.
Alternatively, set a breakpoint in your application right after creating the socket, and then use netstat -ano (on Windows) to check which process id is associated with the other endpoint of your socket (which should be on your machine if you connect to localhost).
I would suggest you to disable your antivirus, but in some cases even that does not help to unload their broken live TCP scanning driver...
The Socket constructor connects right away and will throw an IOException if it doesn't succeed. So apparently you have connected successfully to a server (this could be one you didn't make yourself).