I recently learn about Socket Programming between client and server. So I thought of doing an exercise of connecting both client and server. However, I have encountered this error message when I try to run the code:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
This is my client class code:
public class clientpart {
public static void main(String[]args) throws UnknownHostException, IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
String host=null;
String answer; String sendMessage; String receivedMessage;
InetAddress address = InetAddress.getByName(host);
Socket socket= new Socket(address,port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println("Please answered the following question: ");
System.out.println("What is the subject code for Socket Programming?");
answer = input.nextLine();
sendMessage = answer;
bw.write(sendMessage);
bw.newLine();
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
receivedMessage = br.readLine();
System.out.println("Message received from server : " + receivedMessage);
}
}
This is my server code:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
String answer; String returnedMessage; String reply;
ServerSocket server = new ServerSocket(port);
System.out.println("Server start at port "+port+".");
while(true)
{
socket = server.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
answer = br.readLine();
System.out.println("Message sent from client: " + answer);
if("NET 3202".equals(answer) || "net 3202".equals(answer) || "NET3202".equals(answer) || "net3202".equals(answer)){
reply = "Correct!";
returnedMessage = reply;
}
else{
reply = "Wrong!";
returnedMessage = reply;
}
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
System.out.println("Message replied to client: "+returnedMessage);
bw.flush();
}
}
}
The full error message is:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:244)
at clientpart.main(clientpart.java:13)
C:\Users\PeiErn\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
I hope someone can help me, thanks.
There are 2 issues in your program:
You use the port 80 which is part of the well-known ports or system ports (0 to 1023), so you need to launch your server with the admin rights or change it for 8080 for example.
You forgot to call bw.newLine() after each bw.write(sendMessage) such that it waits for ever since on the other side you call br.readLine() which means that it waits for an entire line while you don't send the end of line characters.
Change your code for this:
Server part:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
...
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
...
Output:
Server start at port 8080.
Accepted
Message sent from client: net3202
Message replied to client: Correct!
Client part:
public class clientpart {
public static void main(String[]args) throws IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
...
bw.write(sendMessage);
bw.newLine();
bw.flush();
...
Output:
Please answered the following question:
What is the subject code for Socket Programming?
net3202
Message sent to server: net3202
Message received from server : Correct!
Related
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream());
PrintWriter pw = new PrintWriter(os);
os.write(str);
os.flush();
}
}
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("Server is started");
ServerSocket ss = new ServerSocket(5643);
System.out.println("Server is waiting");
Socket s = ss.accept();
System.out.println("Client Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println("Client Data : "+str);
}
}
Exception in thread "main" java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
at java.net.Socket.<init>(Socket.java:451)
at java.net.Socket.<init>(Socket.java:228)
In Client.java change this line:
String str = "Sagar Tanwar";
to:
String str = "Sagar Tanwar\r\n";
Your server expects to read a full line (br.readLine()) and it continues to read until your client stays connected. Once the client disconnects, an exception is thrown because the server was unable to read a new line.
Side notes
On my system:
your client throws: java.net.ConnectException: Connection refused: connect - if the server is not active
your server throws: java.net.SocketException: Connection reset - if the server can't read a full line from the client
Everything will work for you if you close the connections at the end of the client class.
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
OutputStreamWriter os = null;
try {
os = new OutputStreamWriter(s.getOutputStream());
os.write(str);
os.flush();
} finally {
if (os != null)
os.close();
}
or with "try with resources"
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
try (OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream())) {
os.write(str);
os.flush();
}
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream());
PrintWriter pw = new PrintWriter(os);
os.write(str);
os.flush();
}
}
I recently learn about Socket Programming between client and server. So I thought of doing an exercise of connecting both client and server. However, I have encountered this error message when I try to run the code:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
This is my client class code:
public class clientpart {
public static void main(String[]args) throws UnknownHostException, IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
String host=null;
String answer; String sendMessage; String receivedMessage;
InetAddress address = InetAddress.getByName(host);
Socket socket= new Socket(address,port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println("Please answered the following question: ");
System.out.println("What is the subject code for Socket Programming?");
answer = input.nextLine();
sendMessage = answer;
bw.write(sendMessage);
bw.newLine();
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
receivedMessage = br.readLine();
System.out.println("Message received from server : " + receivedMessage);
}
}
This is my server code:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
String answer; String returnedMessage; String reply;
ServerSocket server = new ServerSocket(port);
System.out.println("Server start at port "+port+".");
while(true)
{
socket = server.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
answer = br.readLine();
System.out.println("Message sent from client: " + answer);
if("NET 3202".equals(answer) || "net 3202".equals(answer) || "NET3202".equals(answer) || "net3202".equals(answer)){
reply = "Correct!";
returnedMessage = reply;
}
else{
reply = "Wrong!";
returnedMessage = reply;
}
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
System.out.println("Message replied to client: "+returnedMessage);
bw.flush();
}
}
}
The full error message is:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:244)
at clientpart.main(clientpart.java:13)
C:\Users\PeiErn\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
I hope someone can help me, thanks.
There are 2 issues in your program:
You use the port 80 which is part of the well-known ports or system ports (0 to 1023), so you need to launch your server with the admin rights or change it for 8080 for example.
You forgot to call bw.newLine() after each bw.write(sendMessage) such that it waits for ever since on the other side you call br.readLine() which means that it waits for an entire line while you don't send the end of line characters.
Change your code for this:
Server part:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
...
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
...
Output:
Server start at port 8080.
Accepted
Message sent from client: net3202
Message replied to client: Correct!
Client part:
public class clientpart {
public static void main(String[]args) throws IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
...
bw.write(sendMessage);
bw.newLine();
bw.flush();
...
Output:
Please answered the following question:
What is the subject code for Socket Programming?
net3202
Message sent to server: net3202
Message received from server : Correct!
Found some similar questions but no answer, so here goes -
Attached code is self contained, compilable and runnable to set up a server on my computer. Socket gets created, and I can do a telnet <ip_address> 9162 or telnet localhost 9162 from my local machine. From a remote host, telnet does not get connected. Any ideas? TIA.
import java.io.*;
import java.net.*;
public class TestServerSocket {
public static void main(String args[]) throws IOException {
final int portNumber = 9162;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while (true) {
pw.print("What's you name? ");
pw.flush();
String str = br.readLine();
if (str.trim().length() == 0)
break;
pw.println("Hello, " + str);
}
pw.close();
socket.close();
}
}
}
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
In this code I use multiple times of retrieve input-output data from two nodes. ... when I use more than two times input output stream it generated this type of error while running this code I need different input and output and that I want to store but unfortunate if I used more than three-time input/output stream it show error
public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to
client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}
public class client {
private static Socket socket;
//public void connect() throws UnknownHostException, IOException{
//}
public void first() throws IOException{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
String sendMessage1="3333";
bw.write(sendMessage1);
bw.flush();
//second();
}
public void second1() throws IOException{
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr;
isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
socket.close();
}
public static void main (String argd[]) throws IOException{
client obj1 = new client();
obj1.first();
}
-----------------------------------------
error
Message received from client is 2
Message sent to the client is Second
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
InputStream and OutputStream are intended to work with a single source and destination. Once you obtain an InputStream that reads from file/socket/whatever source you can use it for multiple consecutive reads. But once you are done reading from that source you need to invoke close() method on your stream.
Not closing your stream is classic reason for a memory leak in Java. In fact for that reason you ALWAYS expected to surround the usage of your source with try catch and always invoke close() method in finally statement. So to insure that it is always invoked. Further more, since close() method itself can cause an Exception, within final statement you need to surround it with its own try-catch. Starting from java 7 there is a new feature called "try with resources" that deals with this particular issue.
Please read about it here
I'm trying to build a simple server client program, I'm trying to figure a way how to prompt the CLIENT if the server is down, or if the server is up and loses connection
Question: How can I prompt the client that he's disconnected because the Server shuts down or loses connection
SERVER
public class Server{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("Client has connected!");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
CLIENT
public class Client{
private static Socket socket;
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
while(true)
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//System.out.println("You're now connected to the Server"); /*this should only print once */
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number;
number=input.next();
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (IOException exception)
{
//System.out.println("Server is still offline");/*This should only print once*/
}
How can I prompt the client that he's disconnected because the Server shuts down or loses connection?
You can use the catch block to prompt the client in Client class which will be executed when IOException occurs
} catch (ConnectException e) { //When the connection is refused upon connecting to the server
//promt the user here
System.out.println("Connection refused");
break; //to quit the infinite loop
} catch (IOException e) { //when connection drops, server closed, loses connection
//promt the user here
System.out.println("Disconnected from server");
break; //to quit the infinite loop
}