Connection refused from client to server - java

I am learning about Sockets in Java and I am only missing how to receive back response from the server.
Following How to send string array object and How to send and receive serialized object in socket channel, I am trying to ask the user to pick as much as he wants out of choices:
1 - 2 - 3 - 4
And then I want to split and send them as an array to a server, where the server should send back the number of choices the user has picked.
For example if the user chose
2 3 4 1 2 3 4 1
Server should return
8
server is sending response fine, but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection
refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native
Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown
Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at
java.net.PlainSocketImpl.connect(Unknown Source) at
java.net.SocksSocketImpl.connect(Unknown Source) at
java.net.Socket.connect(Unknown Source) at
java.net.Socket.connect(Unknown Source) at
java.net.Socket.(Unknown Source) at
java.net.Socket.(Unknown Source) at
ClientClass.main(ClientClass.java:26)
I am not sure why the issue. Any help?
My Client:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ClientClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// take order and convert it to array of choices
Scanner myScanner = new Scanner(System.in); // take from user
System.out.println("Enter all your choices seperated by space:");
System.out.println("Choices are: 1- 2- 3- 4");
String orderString = myScanner.next();
orderString += myScanner.nextLine();
String orderArray[] = orderString.split(" ");
// send request to server
Socket mySocket = new Socket("127.0.0.1", 4444); // create a socket
ObjectOutputStream out = new ObjectOutputStream(mySocket.getOutputStream());
out.writeObject(orderArray);
// get response from server
InputStream is = mySocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
}
My Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ServerClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// receive
ServerSocket myServerSocket = new ServerSocket(4444); // create a server socket
Socket mySimpleSocket = myServerSocket.accept(); // accept requests
ObjectInputStream ois = new ObjectInputStream(mySimpleSocket.getInputStream());
String[] choices = (String[]) ois.readObject();
// send back response
OutputStream os = mySimpleSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(choices.length);
System.out.println("Message sent to the client is "+choices.length);
bw.flush();
}
}

server is sending response fine
Rubbish. The server isn't even getting an incoming connection, let alone reading the request, let alone sending a response.
but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection refused: connect at
On this evidence the server wasn't even running. Certainly not running in the same host as the client, which is what is required by new Socket("127.0.0.1", 4444).

Related

I get socket exception (connection reset ) on client side whenever I try to read data form the server

when I run the code for the code below for the firs time it runs just fine
then I try to add more code (like creating buffered input stream in server side and try to read back from the client ) and run it again it gives me this exception in client side
Exception in thread "main" java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:976)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:297)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:178)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:329)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:396)
at client.main(client.java:20)
when I remove the added code and run it with just the reader in client side it still wont work
it wont work unless I removed the inputstream from client side
this is the server side
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class server
{
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8080);
Socket client = server.accept();
PrintWriter out= new PrintWriter(client.getOutputStream(),true);
out.write("dfdawdadwawdw");
}
}
and this is the client side
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
import jdk.internal.jshell.tool.resources.l10n;
public class client {
public static void main(String[] args) throws Exception {
Socket java = new Socket("localhost",8080);
InputStreamReader in = new InputStreamReader(java.getInputStream());
BufferedReader bufferedreader = new BufferedReader(in);
System.out.println(bufferedreader.readLine());
}
}
In the server code try out.println instead of out.write:
// Server side code
import java.io.*
import java.net.*
public class server () {
public static void main(String[] args) {
ServerSocket server = new ServerSocket(8080);
Socket client = server.accept();
PrintWriter out= new PrintWriter(client.getOutputStream(),true);
out.println("dfdawdadwawdw");
}
}
This worked for me.
According to BufferedReader.readLine(), the readLine function expects a termination.
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).
So the problem is caused by your bufferedReader that tries to read a line breaker from a stream that has nothing in it anymore.
Also please refer to java.net.SocketException: Connection reset.

Why is it showing me that connection has not established?

Why java is showing this output for every port connections And is it require any thing like basic frame or package in java other than these.i am working on basic server client program first is client and second is server.I tried basic code for only connection.but it shows this output every time
import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
}
}
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date: " + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
THIS IS OUTPUT
output:=
Exception in thread "main" java.net.ConnectException: Connection timed out: conn
ect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at DateClient.main(DateClient.java:8)
You are using the DNS resolver to get the local hostname, and you encounter a timeout when connecting to it, so:
either your DNS resolver is configured to a host that is down or filtered by a firewall,
or the DNS resolver resolves the local host name to an IP that is not the one of your server and is down or filtered by a firewall.
These are the two main cases for which you may have such a timeout, instead of a host unreachable or port unreachable error.
So, replace the line:
Socket soc = new Socket(InetAddress.getLocalHost(),5217);
by this one:
Socket soc = new Socket(InetAddress.getLoopbackAddress(), 5217);
to solve your problem.

Java Socket Connection Failure

I have a server code in Java which I run on my machine and my friend has a client code which runs on his machine. When he enters my IP so as to connect to my server and get the date, connection fails and nothing happens. Note that when I run server and client programs on my own machine and enter localhost as the address, connection is successful and I get the date message correctly. I'm looking for possible errors and problems causing this.
Server code in Java:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9999);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
}
Client code in Java:
import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9999:");
Socket s = new Socket(serverAddress, 9999);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Some routers might isolate computers in different networks. Try it with both computers on Wifi or both wired to the router. Are your IPs on the same network? Can you see your friend's computer on the network? There might also be some security configurations on your router.
Other than that and firewall issue (which you have disabled), the code looks like it should work fine.

Sending "227 \r\n" on port 21 terminates connection

Let me start off by stating that this is my first post here on stackoverflow. Feel free to point out any mistakes made while posting.
Okay, so the problem at hand is a little weird. I'm currently implementing the FTP protocol for my project, but ran into the following problem. Every time my application has to return the message "227 Entering Passive Mode (<ip1>,<ip2>,<ip3>,<ip4>,<port1>,<port2>)." the connection is terminated. The stack trace being:
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlush(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at Server$1.run(Server.java:30)
at java.lang.Thread.run(Unknown Source)
In order to replicate the behaviour I decided to build a prototype which accepts a connection on port 21 and sends the message "227 " after recieving an arbitrary message from the client. This also results in the connection being terminated.
(Prototype Code snippet:)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
ServerSocket server = null;
try {
server = new ServerSocket(21);
} catch (IOException e1) {
e1.printStackTrace();
}
while(true) {
try {
Socket client = server.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
writer.write("227 \r\n");
writer.flush();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
(I'm aware the above code is not the nicest implementation, but is imho sufficiently adequate for representing the problem at hand.)
After some tinkering with the prototype I have figured out that this behaviour only occurs when sending "227 " in conjunction with using port 21 (e.g. using port 4500 works just fine).
Now of course the obvious workaround to this is to avoid using port 21, but i would like to know why i'm experiencing this. Any input on the matter is highly appreciated ;) (just to make sure, i'm using JavaSE-1.7).

Finding Java server time and client time

I tried this code from this site server client code
It worked perfect on my machine,I first ran the server code then the client code.
And I got the time.
I tried putting the server side code on to another PC and running it on eclipse there,similarly I tried running client side code from eclipse on my side but wasn't successful.
It gave me the following error:
Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at sample.servertime.main(servertime.java:13)
Am I doing it correct or is it wrong what I am doing.Need help.
Here are the 2 codes.
// Date Client
import java.io.*;
import java.net.*;
class DateClient
{
publicstaticvoid main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(
new InputStreamReader(
soc.getInputStream()
)
);
System.out.println(in.readLine());
}
}
// Date Server
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
publicstaticvoid main(String args[]) throws Exception
{
InetAddress locIP = InetAddress.getByName("192.168.1.21");
ServerSocket s= new ServerSocket(5217, 0, locIP);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date" + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
In the server part you've hard coded the ip address for the server:
InetAddress locIP = InetAddress.getByName("192.168.1.21");
ServerSocket s= new ServerSocket(5217, 0, locIP);
When you run it on the other machine the address will be different and therefore it can't be bound unless you change it.
You could change it to bind to all addresses like:
ServerSocket s = new ServerSocket(5217);
Also, the client will always try to connect to the local machine:
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
So if you want to have the client connect to a server on another machine InetAddress.getLocalHost()has to be changed to the address of the server.

Categories

Resources