Server not receiving in socket communication - java

I'm trying to make a Java program in which the server generates a random number and, after establishing a connection with a client, lets it guess the number. However, they both don't seem able to receive each others' messages.
Server side:
package numberguessserv;
import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class NumberGuessServ {
public static void main(String[] args) {
Scanner inpkb = new Scanner(System.in);
Random randomGenerator = new Random();
int randomNum = randomGenerator.nextInt(10);
String number = Integer.toString(randomNum);
int port;
boolean isGuessed = false;
String msgReceived;
Socket connect = new Socket();
System.out.print("port: ");
port = inpkb.nextInt();
try {
ServerSocket clSock = new ServerSocket(port);
System.out.println("Waiting...");
connect = clSock.accept();
System.out.println("Connection established with"+connect.getInetAddress());
InputStreamReader isr = new InputStreamReader(connect.getInputStream());
BufferedReader isrBuff = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter(connect.getOutputStream());
BufferedWriter oswBuff = new BufferedWriter(osw);
while (!isGuessed) {
msgReceived = isrBuff.readLine();
System.out.println("Number received: "+msgReceived);
if (msgReceived.equals(number)) {
isGuessed = true;
oswBuff.write("Right!");
oswBuff.flush();
}
else {
oswBuff.write("Wrong!");
oswBuff.flush();
}
if (isGuessed)
System.out.println("Number was guessed right.");
else
System.out.println("Number was guessed wrong.");
}
}
catch (Exception ex) {
System.out.println("An exception has occurred: "+ex);
}
finally {
try {
connect.close();
}
catch (Exception ex) {
System.out.println("An exception has occurred: "+ex);
}
}
}
}
Client side:
package numberguessclient;
import java.io.*;
import java.util.Scanner;
import java.net.*;
public class NumberGuessClient {
public static void main(String[] args) {
Scanner inpkb = new Scanner(System.in);
int port;
String IP;
boolean isGuessed = false;
String number, msg;
Socket serv = new Socket();
System.out.print("IP: ");
IP = inpkb.next();
System.out.print("port: ");
port = inpkb.nextInt();
try {
serv = new Socket(IP,port);
System.out.println("Connetion established with"+serv.getInetAddress());
InputStreamReader isr = new InputStreamReader(serv.getInputStream());
BufferedReader isrBuff = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter(serv.getOutputStream());
BufferedWriter oswBuff = new BufferedWriter(osw);
while (!isGuessed) {
System.out.print("number: ");
number = inpkb.next();
oswBuff.write(number);
oswBuff.flush();
System.out.println("Number sent.");
msg = isrBuff.readLine();
System.out.println("The reply was received: "+msg);
if (msg.equals("Right!")) {
isGuessed = true;
System.out.println(msg);
}
else {
System.out.println(msg+"\nTry again...");
}
}
}
catch (Exception ex) {
System.out.print("An exception has occurred: "+ex);
}
finally {
try {
serv.close();
}
catch (Exception ex) {
System.out.print("An exception has occurred: "+ex);
}
}
}
}

The readLine() waits for the end of line. Unless and until it gets a new line character, it will wait up there reading.
So, you need to give a new line characer '\n' every time you give an input to the output stream so that the readLine() reads a new line character and does not wait.
Currently in your code, you need to give a new line character everytime you are giving input by doing the following:
oswBuff.write("any message");
oswBuff.write('\n'); //add this statement everywhere you are writing to the output stream
oswBuff.flush();
This complies well for both the server as well as client.

That's expected. Both ends read using
isrBuff.readLine();
So, they both expect the other end to send a line. But none of them sends a line. They both do
oswBuff.write(number);
oswBuff.flush();
That sends some characters, but doesn send any newline character. The receiving end doesn't have any way to know that the end of line has been reached, and it thus continues blocking until it receives the EOL.

Related

Java - Getting error "Socket is closed" when my Client class connects on my Server class

I made two classes in Java named Server.java and Client.java. The Server is listening to a port and is waiting for a Client to connect (using sockets). When the client connects he can type a pair of numbers separated by "space" and if that pair exists in my edge_list.txt file the Server returns "1" to the client, if not it returns "0". After I completed my initial project I wanted to also use Threads so that it can handle multiple users at once, but when the Client connects I get -> java.net.SocketException: Socket is closed.
I reviewed my code and try using flush() instead of close(). Also, I thought I was closing the socket before the user can read the file, but it didn't seem that was the case. Below I will have the Server.java code block and not the Client.java, cause it doesn't seem to be the problem.
Server.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static final int PORT = 9999;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is listening on port " + PORT);
while (true) {
try (Socket socket = serverSocket.accept()) {
System.out.println("Client connected: " + socket);
new ClientHandler(socket).start();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ClientHandler extends Thread {
private Socket socket;
ClientHandler(Socket socket){
this.socket = socket;
}
#Override
public void run() {
try {
//Creating Sockets and Streams
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output));
while (socket.isConnected() && !socket.isClosed()) {
//Reading what the Client types
String request = reader.readLine();
//Split the values with "space" and store them in an array,
//then parse those values to two integers
String[] values = request.split(" ");
int A = Integer.parseInt(values[0]);
int B = Integer.parseInt(values[1]);
//Check if the pair in the file exists using checkPairInFile() method
boolean exists = checkPairInFile(A, B);
//if it does print 1 else 0
writer.println(exists ? "1" : "0");
//Flush the output to send the response back to the client
writer.flush();
}
//Print the disconnected user
System.out.println("Client disconnected: " + socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean checkPairInFile(int A, int B) {
try (Scanner scanner = new Scanner(new File("edge_list.txt"))) {
//Scanning the file lines
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Split the values with "space"
String[] values = line.split(" ");
//Parse the values from String -> Int
int a = Integer.parseInt(values[0]);
int b = Integer.parseInt(values[1]);
//if both exist return true
if (A == a && B == b) {
return true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
P.S. Thanks in advance for your help, in case this is problem with my Client.java file I will update the post.
This part:
try (Socket socket = serverSocket.accept()) {
System.out.println("Client connected: " + socket);
new ClientHandler(socket).start();
}
accepts a socket, then prints a message, then starts a new thread, then closes the socket. At some point later the new thread finishes starting up and tries to use the socket and realizes it was already closed.
try (...) {...} (officially called try-with-resources) always closes the things when it gets to the }. That's the point of it. If you don't want to close the socket at the } then you shouldn't use this type of statement.

Why is my else if code not running on a Server side? I want to get the input printed given number of times loop is running on client side

MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(5001);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
if ("Hi".equals(str)){
dout.writeUTF("How are you?");
} else if ("Bye".equals(str)){
dout.writeUTF("Thankyou! Have a Good day!");
} **else if (str != null)){
try {
String numbers;
numbers = str.replaceAll("[^0-9]", "");
int number = Integer.parseInt(numbers);
dout.writeUTF("The line is being printed");
for (int i = 0; i < number; i++) {
dout.writeUTF(str.replaceAll("[^a-z,^A-Z]", ""));
}
} catch (Exception e) {
//TODO: handle exception
}**
} else {
dout.writeUTF("Sorry!");
}
dout.flush();
dout.close();
s.close();
ss.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
MyClient.java
import java.io.*;
import java.net.*;
import java.util.*;
public class MyClient {
public static void main(String[] args) {
try{
Scanner sc = new Scanner(System.in);
Socket s=new Socket("localhost",5001);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
String str1= sc.nextLine();
dout.writeUTF(str1);
dout.flush();
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
dout.close();
dis.close();
s.close();
} catch(Exception e) {
System.out.println(e);}
}
}
I am giving input to the server from the client-side and want that input to be printed given a number of times on the client-side. But not able to do that. Can anyone let me know what mistake I am making here? It is replying to message "Hi" and "Bye", everything else is working fine.
The following is your code with my corrections.
(Notes after the code.)
Class MyServer
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args) {
try (ServerSocket ss = new ServerSocket(5001)) {
Socket s = ss.accept();// establishes connection
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
String str = dis.readUTF();
System.out.println("message= " + str);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
if ("Hi".equals(str.trim())) {
dout.writeUTF("How are you?");
}
else if ("Bye".equals(str)) {
dout.writeUTF("Thankyou! Have a Good day!");
}
else if (str != null) {
try {
String numbers;
numbers = str.replaceAll("[^0-9]", "");
int number = Integer.parseInt(numbers);
dout.writeUTF("The line is being printed");
for (int i = 0; i < number; i++) {
dout.writeUTF(str.replaceAll("[^a-z,^A-Z]", ""));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
dout.writeUTF("END");
dout.flush();
}
catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(2000L);
}
catch (InterruptedException xInterrupted) {
// Ignore.
}
}
}
Class MyClient
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.util.Scanner;
public class MyClient {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
try (Socket s = new Socket("localhost", 5001)) {
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(str1);
dout.flush();
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
String str = dis.readUTF();
while (!"END".equals(str)) {
System.out.println("message= " + str);
str = dis.readUTF();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Sending and receiving data via sockets is not instantaneous. Method readUTF will wait until there is data to read. It will read all the data sent in the last invocation of method writeUTF. Method readUTF will wait indefinitely. Hence the server needs to send notification to the client that there is no more data to send. In the above code I send the string END to indicate the end of the data that the server is sending. Note also that you only need to close resources that you explicitly create. In class MyServer, this means ServerSocket only. I use try-with-resources to ensure that ServerSocket is closed.
Similarly, in class MyClient, the only resource that needs to be explicitly closed is the Socket – which I again do using try-with-resources.
If the server terminates, the socket is closed. Hence, in class MyServer, after sending data to the client, the server waits for two seconds which is hopefully enough time for the client to read that data.

iterative dictionary server in java

what it do..
1. an iterative dictionary server that is listening clients requests..
2. connection will be established..
3. server will accept input string from client..
4. then server will search meaning of string from a file..
5. then server will return meaning to the client..
problem is with the while loop of server.. if it finds word it will send that word's meaning to client..fine.. but if word is not found... this
if(d.equals(null)){
input="No knowledge";
out.println(input);
out.flush();
}
doesn't execute... client says null and server says null exception...
what i am doing wrong here... i'm not getting it...!!
i have tried to changed this code...
client-server online dictionary program in java
client:
import java.io.;
import java.net.;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class DCC1 {
public static void main(String[] args) throws IOException {
final int PORT = 8888;
Socket s = null;
PrintWriter out = null;
try {
s = new Socket("localhost", PORT);
out = new PrintWriter(s.getOutputStream()); // Output stream to the server
}
catch (UnknownHostException ex) {
System.err.println("Unknown host: " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
catch (IOException ex) {
System.err.println("Cannot get I/O for " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
Scanner user = new Scanner(System.in); // Scanning for user input
System.out.print("Enter String: ");
String input;
input = user.next(); // Hold the input from the user
out.println(input); // Send it to the server
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream( )));
System.out.println(br.readLine());
out.close();
s.close();
}
}
server:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class DSC1
{
public static void main(String[] args) throws IOException
{
final int PORT = 8888;
final String FILE_NAME = "dictionary.dat";
ServerSocket server = new ServerSocket(PORT);
Socket s = null;
PrintWriter out = null;
Scanner in = null;
FileInputStream fin = null;
ObjectInputStream oin = null;
while (true)
{
try
{
s = server.accept();
}
catch (IOException ex)
{
System.err.println("Accept failed");
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
System.out.println("Accepted connection from client");
try
{
in = new Scanner(s.getInputStream()); // Input stream from the client
out = new PrintWriter(s.getOutputStream()); // Output stream to the client
String temp = in.next(); // String holding the word sent from the client
System.out.println("From the client " + temp);
String input = null;
fin = new FileInputStream(FILE_NAME);// The dictionary file
oin = new ObjectInputStream(fin);
dictionary d = (dictionary)oin.readObject();
while(d!= null)
{
System.out.println("in loop...");
if(d.name.equals(temp)){
input=d.meaning;
d.printDic();
out.println(input);
out.flush();
break;
}
d = (dictionary)oin.readObject();
if(d.equals(null))
{
input="No knowledge";
out.println(input);
out.flush();
}
}
}
catch (ClassNotFoundException|IOException ex)
{
System.err.println("Exception: " + ex.getMessage());
System.out.println("Closing connection with client");
in.close();
System.exit(1);
}
in.close();
}
}
}
Don't use d.equals(null). If you want to check if d is null, just do if (d==null).
Why? There's no way this can return true, so probably that's the reason why this code never executes and you don't get what you expect.

Threads/Sockets in a client server mini application

I basically try to make a simple domain resolver using sockets.
I am pretty far and I its working how it is now. Except my main function where I try to make a thread which keeps listening and waiting for another call. After I type www.google.com it gives me the address but when I try it again, it does nothing. I think the socket closes or something. I wanted to use threads and while loops but I'm struggling with this problem for hours.
Client side ( EchoClient.java )
package tetst222;
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args) throws IOException
{
try
{
Socket sock = new Socket("localhost", 1350);
PrintWriter printout = new PrintWriter(sock.getOutputStream(),true);
InputStream in = sock.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
while((line = bin.readLine()) != null)
{
System.out.println(line);
}
//sock.close();
}
catch(IOException ioe)
{
System.err.println(ioe);
}
}
}
And this code:
Server side ( EchoServer.java )
package tetst222;
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class EchoServer //implements Runnable
{
public static void main(String[] args) throws IOException
{
try
{
ServerSocket sock = new ServerSocket(1350);
while(true)
{
// open socket
Socket client = sock.accept();
PrintWriter printout = new PrintWriter(client.getOutputStream(),true);
printout.println("Je bent succesvol verbonden met de host");
printout.println("Geef een hostnaam op waarvan je het IP-adres wilt achterhalen:");
//get input from client
InputStream in = client.getInputStream();
BufferedReader bufin = new BufferedReader(new InputStreamReader(System.in));
/*
Thread t = new Thread();
t.start();
*/
String host = "";
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
host = sc.nextLine();
try
{
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}catch (IOException e) {
System.err.println("IOException: " + e);
}
client.close();
}
}catch(IOException ioe)
{
System.err.println(ioe);
}
}
/*
public void run() {
String host = "";
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
host = sc.nextLine();
try
{
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}catch (IOException e) {
System.err.println("IOException: " + e);
}
}
*/
}
Your server don't handle client requests. It wait for new client (socket.accept) and read default system input (System.in) not a socket, and after just close client connection.
it look like:
public static void main(String[] args) throws IOException {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
String host = sc.nextLine();
try {
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
} catch (UnknownHostException uhe) {
System.out.println(uhe.toString());
}
}
}
At the client side you should read address from console, write it to socket (send request), then read data from socket (take response) and out to console;
At the server side you must accept client connection (socket.accept), read data from socket (take request), handle it (InetAddress.getByName(host)) and send response back to the client socket.

java.lang.NullPointerException and java.net.SocketException

I’m trying to socket program in Java. Here the client sends a string which should be reversed by the server and sent back to the client. The server is a multithreaded server. Here is the client-side code:
import java.io.*;
import java.net.*;
class ClientSystem
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
int port = 1234;
Socket clientsocket = null;
DataOutputStream output =null;
BufferedReader input = null;
try
{
clientsocket = new Socket(hostname,port);
output = new DataOutputStream(clientsocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
}
catch(Exception e)
{
System.out.println("Error occured"+e);
}
try
{
while(true)
{
System.out.println("Enter input string ('exit' to terminate connection): ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputstring = br.readLine();
output.writeBytes(inputstring+"\n");
//int n = Integer.parseInt(inputstring);
if(inputstring.equals("exit"))
break;
String response = input.readLine();
System.out.println("Reversed string is: "+response);
output.close();
input.close();
clientsocket.close();
}
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
Here is the server side code:
import java.io.*;
import java.net.*;
public class ServerSystem
{
ServerSocket server = null;
Socket clientsocket = null;
int numOfConnections = 0, port;
public ServerSystem(int port)
{
this.port = port;
}
public static void main(String[] args)
{
int port = 1234;
ServerSystem ss = new ServerSystem(port);
ss.startServer();
}
public void startServer()
{
try
{
server = new ServerSocket(port);
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
System.out.println("Server has started. Ready to accept connections.");
while(true)
{
try
{
clientsocket = server.accept();
numOfConnections++;
ServerConnection sc = new ServerConnection(clientsocket, numOfConnections, this);
new Thread(sc).start();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
public void stopServer()
{
System.out.println("Terminating connection");
System.exit(0);
}
}
class ServerConnection extends Thread
{
BufferedReader br;
PrintStream ps;
Socket clientsocket;
int id;
ServerSystem ss;
public ServerConnection(Socket clientsocket, int numOfConnections, ServerSystem ss)
{
this.clientsocket = clientsocket;
id = numOfConnections;
this.ss = ss;
System.out.println("Connection "+id+" established with "+clientsocket);
try
{
br = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
ps = new PrintStream(clientsocket.getOutputStream());
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
public void run()
{
String line, reversedstring = "";
try
{
boolean stopserver = false;
while(true)
{
line = br.readLine();
System.out.println("Received string: "+line+" from connection "+id);
//long n = Long.parseLong(line.trim());
if(line.equals("exit"))
{
stopserver = true;
break;
}
else
{
int len = line.length();
for (int i=len-1; i>=0; i--)
reversedstring = reversedstring + line.charAt(i);
ps.println(""+reversedstring);
}
}
System.out.println("Connection "+id+" is closed.");
br.close();
ps.close();
clientsocket.close();
if(stopserver)
ss.stopServer();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
I get a java.lang.NullPointerException on the server side code when I enter the string and when i try to re-enter the string I get a java.net.SocketException: Socket closed exception.
Client side output:
Enter input string ('exit' to terminate connection):
usa
Reversed string is: asu
Enter input string ('exit' to terminate connection):
usa
Error occured.java.net.SocketException: Socket closed
Server side output:
Server has started. Ready to accept connections.
Connection 1 established with Socket[addr=/127.0.0.1,port=3272,localport=1234]
Received string: usa from connection 1
Received string: null from connection 1
Error occured.java.lang.NullPointerException
I tried a lot but I don't get from where I get these exceptions.
These 3 lines are the culprits in the client code:
output.close();
input.close();
clientsocket.close();
Put them outside of the while loop, and in the finally block:
try {
while(true) {
// client code here
}
} catch (Exception e) {
e.printStackTrace(); // notice this line. Will save you a lot of time!
} finally {
output.close(); //close resources here!
input.close();
clientsocket.close();
}
The issue is that as it was originally, you closed every resource, but in the next iteration, you wanted to use them agai, without initialising them...
Sidenote
Properly handling exceptions including proper logging of them. Always use either a logging framework like log4j
LOG.error("Unexpected error when deionizing the flux capacitor",e);
, or the printStackTrace() method
e.printStackTrace();
And don't forget to include the line numbers in your code, if you post a stacktrace....
EDIT
For the reversed issue:
else
{
int len = line.length();
reversedString=""; //this line erases the previous content of the reversed string
for (int i=len-1; i>=0; i--) { //always use brackets!!!
reversedstring = reversedstring + line.charAt(i);
}
ps.println(""+reversedstring);
}
What happened? The reversedString just grew and grew with each iteration, without getting erased... This is why I like to declare my variables in just the most strict scope I need them.
EDIT
To make the exit command no tkill the server, this can be one (very simple) solution:
In the ServerConnection class:
while(true)
{
line = br.readLine();
System.out.println("Received string: "+line+" from connection "+id);
if(line.equals("exit"))
{
break; //just stop this connection, don't kill server
}
else if(line.equals("stop"))
{
stopserver = true; //stop server too
break;
}
else
{
int len = line.length();
for (int i=len-1; i>=0; i--) {
reversedstring = reversedstring + line.charAt(i);
}
ps.println(""+reversedstring);
}
}
What is happening here? There is a new "command" stop, which makes the server stop, and the exit just exits the client, but does not stop the server itself...
in the 1st run of the loop you are closing all the connections which is causing the issue.
output.close();
input.close();
clientsocket.close();,move it down
Your server is calling br.readLine(); It will wait until the client sends it, but once you send a String you call:
output.close();
input.close();
clientsocket.close();
That will release the resource and result in br.readLine() being null
if (line.equals("exit")) { Here line is null, therefore you cannot call equals.
if ("exit".equals(line)) { You can change it like this to prevent that exception here.
Move the close statements to a finally block, even in the server should, if you have an exception in the while, the close are never reached, that may cause memory leaks.
Client:
} finally {
output.close();
input.close();
clientsocket.close();
}
Server:
} finally {
br.close();
ps.close();
clientsocket.close();
}
Note: you can validate them before closing to ensure they are not null.
You may have to provide a case for the input being null anyway, either exit the loop, usually you would use something like this:
if (null==line || "exit".equals(line)) {
If the client sends a null, something is wrong.

Categories

Resources