Java server socket response to previouse connected client [duplicate] - java

I'm trying to implement a TCP connection, everything works fine from the server's side but when I run the client program (from client computer) I get the following error:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at TCPClient.main(TCPClient.java:13)
I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.
The Server Code:
//TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket(5000);
System.out.println("TCPServer Waiting for client on port 5000");
while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));
PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);
while (true) {
System.out.println("SEND(Type Q or q to Quit):");
toclient = inFromUser.readLine();
if (toclient.equals("q") || toclient.equals("Q")) {
outToClient.println(toclient);
connected.close();
break;
} else {
outToClient.println(toclient);
}
fromclient = inFromClient.readLine();
if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}
}
}
}
}
The Client Code:
//TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String FromServer;
String ToServer;
Socket clientSocket = new Socket("localhost", 5000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
FromServer = inFromServer.readLine();
if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");
ToServer = inFromUser.readLine();
if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}

This exception means that there is no service listening on the IP/port you are trying to connect to:
You are trying to connect to the wrong IP/Host or port.
You have not started your server.
Your server is not listening for connections.
On Windows servers, the listen backlog queue is full.

I would check:
Host name and port you're trying to connect to
The server side has managed to start listening correctly
There's no firewall blocking the connection
The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out why it hasn't. Wireshark may help you on this front.

You have to connect your client socket to the remote ServerSocket. Instead of
Socket clientSocket = new Socket("localhost", 5000);
do
Socket clientSocket = new Socket(serverName, 5000);
The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It's not the name that is important, it's all about IP addresses...

I had the same problem, but running the Server before running the Client fixed it.

One point that I would like to add to the answers above is my experience-
"I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error"
Point to note - When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response
so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.
To get IP for your local machine, you can use ipconfig command on cmd
you will get IPv4 something like 192.68.xx.yy
Voila ..that's your machine's IP where you have your server hosted.
use it then instead of localhost
http://192.168.72.66/my_api/login.php
Note - you won't be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)

I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.
$ sudo vmq-admin listener show
to show the list o allowed ips and ports for vernemq
$ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000
to add any ip and your new port. now u should be able to connect without any problem.
Hope it solves your problem.

Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn't understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.
The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.

In my case, I gave the socket the name of the server (in my case "raspberrypi"), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)

In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)

i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)
so be careful where to close your Socket

I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.
This code works for me.
ClientDemo.java
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket socket = new Socket("127.0.0.1", 55286);
OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
os.write("Santosh Karna");
os.flush();
socket.close();
}
}
and
ServerDemo.java
public class ServerDemo {
public static void main(String[] args) throws IOException {
System.out.println("server is started");
ServerSocket serverSocket= new ServerSocket(55286);
System.out.println("server is waiting");
Socket socket=serverSocket.accept();
System.out.println("Client connected");
BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str=reader.readLine();
System.out.println("Client data: "+str);
socket.close();
serverSocket.close();
}
}

I changed my DNS network and it fixed the problem

You probably didn't initialize the server or client is trying to connect to wrong ip/port.

Change local host to your ip address
localhost
//to you local ip
192.168.xxxx

I saw the same error message ""java.net.ConnectException: Connection refused" in SQuirreLSQL when it was trying to connect to a postgresql database through an ssh tunnel.
Example of opening tunel:
Example of error in Squirrel with Postgresql:
It was trying to connect to the wrong port. After entering the correct port, the process execution was successful.
See more options to fix this error at: https://stackoverflow.com/a/6876306/5857023

In my case, with server written in c# and client written in Java, I resolved it by specifying hostname as 'localhost' in the server, and '[::1]' in the client. I don't know why that is, but specifying 'localhost' in the client did not work.
Supposedly these are synonyms in many ways, but apparently, not not a 100% match. Hope it helps someone avoid a headache.

For those who are experiencing the same problem and use Spring framework, I would suggest to check an http connection provider configuration. I mean RestTemplate, WebClient, etc.
In my case there was a problem with configured RestTemplate (it's just an example):
public RestTemplate localRestTemplate() {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", <some port>));
SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
clientHttpReq.setProxy(proxy);
return new RestTemplate(clientHttpReq);
}
I just simplified configuration to:
public RestTemplate restTemplate() {
return new RestTemplate(new SimpleClientHttpRequestFactory());
}
And it started to work properly.

There is a service called MySQL80 that should be running to connect to the database
for windows you can access it by searching for services than look for MySQL80 service and make sure it is running

It could be that there is a previous instance of the client still running and listening on port 5000.

Related

Why TCP/IP server with listening port in java not working

I have written a code in java to interface my computer with a transmitter a transmitter device, with a communication board already implemented and ready to connect via TCP/IP to any server with a specific address IP (say 192.168.2.2) and listening to a specific port number (say 4000).
I followed the exact strep how to create a server side application in Java offering a that listening port, so that I can connect to that transmitter.
I don't understand why when I try to debug the code, it blocks a the line clientSocket = serverSocket.accept(), and throws a timeout exception.
Could someone help me find out where the error might be in my code?
Any help would be greatly appreciated.
Thanks.
Here is the code:
public class Server {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Declares server and client socket, as well as the input and the output stream
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out;
//BufferedReader in;
BufferedReader in;
try{
InetAddress addr = InetAddress.getByName("192.168.2.2");
//Opens a server socket on port 4000
serverSocket = new ServerSocket(4000) ;
//Sets the timeout
serverSocket.setSoTimeout(30000);
System.out.println("Server has connected");
//Create a connection to server
System.out.println("Server listening connection from client ....");
//Listens and waits for client's connection to the server
clientSocket = serverSocket.accept();
// Creates input and output streams to socket
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Reads response from socket
while((in.readLine())!= null ){
System.out.println ( in.readLine() );
}
System.out.println ( "Closing connection ....");
//Terminates connection
clientSocket.close();
serverSocket.close();
System.out.println("Connecton successfully closed");
}
catch(IOException e){
System.out.println(e);
}
}
}
Could someone help me find out where the error might be in my code?
There is no error in your code that could cause this problem. Clearly you haven't configured the device to connect to this server correctly, or the device isn't running, or it isn't connecting, or there is a firewall in the way. Investigate that.
However:
InetAddress addr = InetAddress.getByName("192.168.2.2");
What is this for? It isn't used.
System.out.println("Server has connected");
This is simply not true. The server hasn't connected. At this point all it has done is create a listening socket.
while((in.readLine())!= null ){
Here you are reading a line and throwing it away.
System.out.println ( in.readLine() );
Here you are printing every second line, having thrown every odd line away. The correct way to write this loop is:
String line;
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
Note also that this server will service exactly one client and then exit. There should be a loop around everything from accept() to clientSocket.close(), and if there are multiple devices it should start a new thread per accepted socket to handle the I/O.
You specified timeout of 30 seconds, didn't you? :
serverSocket.setSoTimeout(30000);
So after 30 seconds, no matter whether stopped in debugger or running, this will timeout and throw exception.

How to use Java to listen to port 17, 'qotd'?

The problem is I only found a little description about port 17, also known as "Quote of the date" port. Useless port, does nothing but display a quote which is less than 512 ASCII characters. Could someone give me more information about how to listen to port 17 in Java? I have established a server client socket using port:6017.
Here is the code:
public class DateServer {
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6017);
// now listen for connections
while (true) {
Socket client = sock.accept();
// we have a connection
PrintWriter pout = new PrintWriter(client.getOutputStream(), true);
// write the Date to the socket
pout.println(); // I know something must happens here!!!
// close the socket and resume listening for more connections
client.close();
}
} catch (IOException ioe) {
System.err.println(ioe);
}
}
}
The system runs in Linux and this code is the server end of the program. I am working on the Client part, and try to make the server do the same thing like port 17 then have a client to receive the "quote of the day" from the server.
Ports less than 1024 are privileged and require escalated permissions to run. Run your program as an administrator of your machine with the port set to 17.

Java socket - client and server IP address

I am writing a program with TCP sockets connection between client and server. When the server starts I want to display the IP and port that clients need to use to connect, and when client connects I want the server to show what IP did the client connect from. I am getting confused which command should i use to each of those:
getInetAdress()
getLocalAdress()
getRemoteSocketAdress()
edit
I earlier used int port = 1234 and String IP = "localhost" to test and it worked, but I only used it on one PC, so I think localhost will not work if i start server and client on different computers.
This is server side:
int port = 1234;
...
public void start() {
keepRunning = true;
// create socket
try {
ServerSocket server = new ServerSocket(port);
while (keepRunning) {
display("Waiting for client connections on "
+ server.getInetAddress().getLocalHost()
.getHostAddress() + ":" + port);
Socket conn = server.accept();
if (!keepRunning)
break;
ClientThread t = new ClientThread(conn);
cList.add(t);
t.start();
And this is client:
int port = 1234;
String IP = "localhost";
//these variables can be changed from Client GUI before making connection
...
public boolean start() {
try {
socket = new Socket(IP, port);
} catch (Exception e) {
display("Error connectiong to server:" + e);
return false;
}
try {
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
display("Exception creating new Input/output Streams: " + e);
return false;
}
When i start the server,
display("Waiting for client connections on " + server.getInetAddress().getLocalHost().getHostAddress() + ":" + port);
return this:
Waiting for client connections on 192.168.1.104:1234
which is kind of what i want, but I still cant get it to show me the port. 1234 is a fixed value i used, but I want to use ServerSocket server = new ServerSocket(0); to asign port dynamically, then when i start the client i just put in the values that i got from server and connect.
I tried to use server.getLocalPort() in the display line in server and it returned 55410 or something like that, but when i put this port in client to make connection, it doesn't work. I get Error connectiong to server:java.net.ConnectException: Connection refused: connect. from client
To get the current port that the ServerSocket is listening to, use getLocalPort();
http://download.java.net/jdk7/archive/b123/docs/api/java/net/ServerSocket.html#getLocalPort%28%29
getLocalPort
public int getLocalPort()
Returns the port number on which this socket is listening.
If the socket was bound prior to being closed, then this method will continue to return the port number after the socket is closed.
Edit: Just saw your edit. Are you trying to connect by explicitly referencing the IP and Port? If so, and it's still failing, your server machine might be running a firewall. I'd check for that first.

(Client - Server) Java control when Server's serversocket accepts client(s) is not working [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently learning about Sockets and my homework is to create a chat room where multiple clients can talk freely. The hint given by the teacher was that the chat room server only accepts the client when the client attempts to send a message. This homework is supposed to be done without using threads.
Following the hint given, I tried to create unbound ServerSocket and Socket in both the client and the server code. The key idea is that when the client attemps to send a message to the server, the client code would connect the unbound Socket, which will then trigger the server to connect the unbound ServerSocket and to accept the client.
However, when I run the code, both the server and client code are running, and they claim that all the connections are made, but I could not transmit messages between the client and the server at all.
I have tried finding answers online, but I could not find any. I would like to ask if my way of deciding when the server accepts the client is correct.
my ChatRoom Server:
public class ChatRoom {
public static void main(String[] args) throws Exception {
int portNum = 4321;
ServerSocket serverSocket = new ServerSocket();
int count = 1;
while (true) {
// redeclare everything each round
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
String inputLine = null;
// accept each time round
serverSocket.bind(new InetSocketAddress(portNum));
socket = serverSocket.accept();
System.out.println("newly accepted!");
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
if (!((inputLine = in.readLine()).equals("Bye"))) {
System.out.println("Client says: " + inputLine);
out.println(stdIn.readLine());
out.flush();
System.out.println("Message Count: " + count);
count++;
}
else {
out.println(inputLine);
serverSocket.close();
socket.close();
out.close();
in.close();
}
}
}
}
my ChatRoomClient:
public class ChatRoomClient {
public static void main(String[] args) throws Exception {
String hostName = "localhost";
int portNumber = 4321;
Socket echoSocket = new Socket(); // creates an unbound socket
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
String userInput;
do {
out = null;
in = null;
stdIn = null;
// each time round the unbound socket attempts to connect to send a message
echoSocket.connect(new InetSocketAddress(hostName, portNumber));
System.out.println("successfully connected");
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
userInput = stdIn.readLine();
out.flush();
System.out.println("Server says: " + in.readLine());
}
while (!userInput.equals("Bye"));
// close everything
echoSocket.close();
in.close();
stdIn.close();
}
}
Thanks!
The hint given by the teacher was that the chat room server only accepts the client when the client attempts to send a message. This homework is supposed to be done without using threads.
The hint given by the teacher doesn't make sense. The client has to connect, then the server accepts. The client can't send a message without connecting first. Maybe the teacher really means that the client shouldn't connect until he has something to send?
Following the hint given, I tried to create unbound ServerSocket and Socket in both the client and the server code. The key idea is that when the client attemps to send a message to the server, the client code would connect the unbound Socket, which will then trigger the server to connect the unbound ServerSocket and to accept the client.
But that won't happen. It's impossible. If you try to connect to a port that isn't listening, you will get a ConnectException. The only way to put the port into listening state is to bind the ServerSocket. There is no magical back-door by which the server can possibly know that the client wants to connect so it should now do the bind.
This homework is supposed to be done without using threads.
Impossible to 'create a chat room where multiple clients can talk freely' that way, unless you are expected to use non-blocking I/O, or abuse the available() facility, or use a connection per message, but then I don't see how you can communicate one client's messages to the other clients, unless you're allowed to batch them up.
There are too many imponderable aspects of this assignment as you have described it. The question as posed doesn't actully make sense, and your proposed solution certainly doesn't. You should just go ahead and write your program the normal way, with a connect, an accept, and some I/O. Get it working while your teacher comes up with a clarification.
Ah... With out using thread for the server you will not be able to serve multiple clients. Anyway, your current codes have issues and your logic are not correct.
Your stdIn should be declare and instantiated outside of the loop, you don't need to keep on creating the stdIn object for each loop.
Your "in" socket accept() and echoSocket.connect() should also be outside of the loop, this is why you are not getting any answer from the server because you are not listening on the same line. It's like your phone, keep on FLASH to dial the new number each time. all point to the same server, but it is different connection.
So, the idea is to establish a connection between server and client (single connection) that can communicate both way (via input and output stream). Then you can loop and talk start with the client, then server receive, then server talk, then client receive then client talk.... until client say Bye...
for more: http://ta.cnci.org/basicirc
thought I would like to update, I managed to solve my problem without using threads. Just sockets haha. Thought it would be good to post my answer for reference..
my ChatRoom Server:
public class ChatRoomServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(4321);
while(true) {
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader
(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = in.readLine();
System.out.println("Client says: " + inputLine);
in.close();
clientSocket.close();
}
}
}
my ChatRoom Client:
public class ChatRoomClient {
public static void main(String[] args) throws Exception {
String hostName = "localhost";
int portNum = 4321;
BufferedReader stdIn = new BufferedReader
(new InputStreamReader(System.in));
while (true) {
String userInput;
userInput = stdIn.readLine();
Socket echoSocket = new Socket(hostName, portNum);
PrintWriter out = new PrintWriter
(echoSocket.getOutputStream(), true);
out.println(userInput);
out.flush();
out.close();
echoSocket.close();
if (userInput.equals("Bye")) {
stdIn.close();
break;
}
}
}
}

Add a timeout when creating a new Socket

I have a local network with DHCP and a few PCs. One of these should be my Server and get automatically connected to all others (clients). My idea was this:
First, I create a server on every client (CServer) that is listening for a client programm from the server (SClient). When the SClient connects to a CServer, the SClient sends the CServer his IP, so he knows there will be the server on this IP. Then after trying all IPs in his IP range (e.g. 192.168.1.xxx), he starts the real server and all the clients connect to the known server IP.
But when I try the following, the SClient just freezes at the first IP, when trying to connect to 192.168.1.0. How can i define a timeout or something similar that lets the SClient drop the unsuccessful connection and going on with 192.168.1.1?
import java.lang.*;
import java.io.*;
import java.net.*;
class SClient {
public SClient() {
for(int i = 120; i < 125; i++){
try{
InetAddress addr = InetAddress.getLocalHost();
String addrs = addr+"";
String ip = addrs.substring(addrs.indexOf("/")+1);
Socket s1 = new Socket("192.168.1." + i, 1254);
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
dos.writeUTF(ip);
dos.close();
s1out.close();
s1.close();
}catch(IOException e){}
}
}
}
and
import java.lang.*;
import java.io.*;
import java.net.*;
class CServer {
public CServer() throws IOException{
ServerSocket s = new ServerSocket(1254);
while(true){
Socket s1=s.accept();
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
dis.close();
s1In.close();
s1.close();
}
}
}
I've found a solution for my problem. It was just initializing the Socket not with
Socket s1 = new Socket("192.168.1." + i, 1254);
but with
Socket s1 = new Socket();
s1.setSoTimeout(200);
s1.connect(new InetSocketAddress("192.168.1." + i, 1254), 200);
Thanks anyway!
It's much easier to do this with UDP. The general logic would be:
Identify a well known port for 'discovery'
Any machine that starts up sends out a 'Query Master Server' message
If a response is not received to that message within a time frame
you define, then the machine that sent it automatically designates
itself as being the server.
Henceforth, any machine that sends out a 'Query Master Server'
message will get a response back from the master, with its IP
address and a 'communication port'
Connect from the new machine to the server on the communication port
and start sending messages.
You might run into situations where more than one server thinks it is the master in this scenario, and then you would need a conflict resolution process, but the outline should give you a general idea of a process that will work for you.

Categories