I am trying to read a file from server and able to do it successfully. However, at the client end the statement after the while loop does not execute at all. Kindly help me with this request. The line asking for client input does not show up at all. Please help
//Client Side Code
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import java.lang.*;
public class oss_client1 {
public static void main(String args[]) throws Exception {
Socket sock = new Socket("127.0.0.1", 2222);
char n1;
int choice;
// reading the file name from keyboard. Uses input stream
BufferedReader keyRead = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader dis = new BufferedReader(
new InputStreamReader(System.in));
// receiving the contents from server. Uses input stream
InputStream istream = sock.getInputStream();
InputStream istream1 = sock.getInputStream();
// sending the file name to server. Uses PrintWriter
OutputStream ostream = sock.getOutputStream();
BufferedReader dRead = new BufferedReader(
new InputStreamReader(istream));
BufferedReader socketRead = new BufferedReader(new InputStreamReader(
istream1));
PrintWriter pwrite = new PrintWriter(ostream, true);
PrintWriter pwrite1 = new PrintWriter(ostream, true);
do {
System.out.println("Enter the website name: ");
String u_input = keyRead.readLine();
pwrite.println(u_input);
String str;
while ((str = dRead.readLine()) != null) {
// reading line-by-line
System.out.println(str);
}
str = dRead.readLine();
System.out.println(str);
dRead.close();
System.out
.print("\nPlease enter the product code which you want to buy: ");
String pcode = dis.readLine();
pwrite1.println(pcode);
String pcode_res = socketRead.readLine();
System.out.print("\nBack from server " + pcode_res + "\n");
System.out.println("\nDo you want to continue(Y/N)");
String n = dis.readLine();
n1 = n.charAt(0);
} while (n1 == 'Y' || n1 == 'y');
pwrite.close();
socketRead.close();
keyRead.close();
}
}
//Server side code
import java.net.*;
import java.util.*;
import java.io.*;
public class oss_server1 {
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
static clientThread t[] = new clientThread[10];
public static void main(String args[]) throws Exception {
int port_number = 2222; // The default port
if (args.length < 1) {
System.out.println("Now using port number=" + port_number);
} else {
port_number = Integer.valueOf(args[0]).intValue();
}
/* Try to open a server socket on port port_number (default 2222) */
try {
serverSocket = new ServerSocket(port_number);
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
clientSocket = serverSocket.accept();
for (int i = 0; i <= 9; i++) {
if (t[i] == null) {
(t[i] = new clientThread(clientSocket, t)).start();
port_number++;
break;
} // end of if loop
} // end for looop
}// end of try loop
catch (IOException e) {
System.out.println(e);
}
} // end of while loop
}
}
class clientThread extends Thread {
DataInputStream is = null;
DataOutputStream dout = null;
Socket clientSocket = null;
clientThread t[];
public clientThread(Socket clientSocket, clientThread[] t) {
this.clientSocket = clientSocket;
this.t = t;
}
public void run() {
try {
System.out.println("Welcome to US ONLINE SHOPPING SYSTEM");
String website = "www.US_OSS.com";
// buffer stream for reading the choice from client
InputStream istream = clientSocket.getInputStream();
InputStream istream1 = clientSocket.getInputStream();
BufferedReader webRead = new BufferedReader(new InputStreamReader(istream));
BufferedReader pcodeRead = new BufferedReader(new InputStreamReader(istream));
// buffer stream reading the file contents
BufferedReader displayRead = new BufferedReader(new FileReader(
"display_client.txt"));
BufferedReader prodRead = new BufferedReader(new FileReader(
"product_list.txt"));
// keeping output stream ready to send the contents
OutputStream ostream = clientSocket.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
String str, str1, pcode;
String fname = webRead.readLine();
if (fname.compareTo(website) != 0) {
pwrite.println("Error 404: NOT FOUND");
} else {
while ((str = displayRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str);
}
displayRead.close();
str = "END OF PRODUCT LIST";
pwrite.println(str);
pcode = pcodeRead.readLine();
System.out.print("\nReceived PCODE is: " + pcode);
pwrite.println(pcode);
}
// pwrite.close();
} // end of try block
catch (IOException e) {
System.out.println(e);
}
} // end of run class
}// end of Client thread class
BufferedReader when reading after EOF will issue IOException
Instead I suggest you use Scanner to read files
Your code would look like...(in ServerSide)
Scanner scnFile=new Scanner(new File("display_client.txt")); //give absolute path if necessary
while(scnFile.hasNext()){
System.out.println(scnFile.nextLine());
}
scnFile.close();
Related
I am using reader.readLine() and sc.nextLine() to simulate the server and client. However, after I typed some words in the scanner, the server responded nothing. I think the problem is thread blocking, but I can't correct it. Could any one help point out where the sticking point is.
Here is the code for server.
public class Server {
public static LocalDateTime currentTime() {
return LocalDateTime.now();
}
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = new ServerSocket(9091);
System.out.println("TCP server ready.\n");
Socket sock = ss.accept();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))) {
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))) {
String cmd;
System.out.println("read in");
while ((cmd = reader.readLine()) != null) {
System.out.println("Rcvd: " + cmd);
if ("time".equals(cmd)) {
writer.write(currentTime() + "\n");
writer.flush();
} else {
writer.write("Sorry?\n");
writer.flush();
}
}
}
}
sock.close();
ss.close();
}
}
The code for client
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
InetAddress addr = InetAddress.getLoopbackAddress();
try (Socket sock = new Socket(addr, 9091)){
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))){
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))){
Scanner sc = new Scanner(System.in);
String cmd;
while (sc.hasNext()) {
cmd = sc.nextLine();
System.out.println("Scanned: " + cmd);
writer.write(cmd);
writer.flush();
String resp = reader.readLine();
System.out.println("Response: " + resp);
}
}
}
}
Use this in Client:
writer.write(cmd + "\n");
since the server read lines.
I am creating a chat program between a server and a client but is run by a main function file.
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
All three files need to be able to access String args[] in the main function file because that is how it gets the port number
Right now the program is able to send and receive one message at a time successfully (see screenshot)
What changes can I make to the code that will allow me to send and receive multiple messages? (probably involves the use of java threads)
Code of main function file:
import java.io.IOException;
public class MainThread
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
}
i=args.length + 20;
}
}
}
Code of Server File:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class ServerThread
{
private String[] serverArgs;
public Socket socket;
public boolean keepRunning = true;
int ConnectOnce = 0;
public ServerThread(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
//run method of ServerRecieve
public void run() throws IOException
{
try
{
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
}
while(keepRunning)
{
//Reading the message from the client
//BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
//Run method of ServerSend
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Code of Client file:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ClientThread implements Runnable
{
int ConnectOnce = 0;
private String[] clientArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
public ClientThread(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
if(ConnectOnce == 0)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
ConnectOnce = 4;
}
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
#Override
public void run()
{
// TODO Auto-generated method stub
}
}
Currently I can only send and receive one line of text at a time, what changes can I make to the code that will allow me to send and receive multiple messages?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to create a program where a client and server send text messages to each other (in utf-8 string format) similar to how two phones text message each other. Eventually I will need to create four lines (two to encode/decode utf-8 string on server side) (two to encode/decode utf-8 string on client side) This program uses two threads, one for the client one for the server.
Screenshot of error in mac terminal (command prompt)
There were no errors before I changed the following lines of code:
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
There are three files: the main function file, the server file, and the client file. When the main function file runs, if the "-l" command line argument is present, the server file will run, otherwise the client will run.
Server file (DirectMessengerServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
private static Socket socket;
boolean KeepRunning = true;
void ServerRun(String[] args)
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[1]);
System.out.println("Port number is: " + port_number1);
ServerSocket serverSocket = new ServerSocket(port_number1);
//SocketAddress addr = new InetSocketAddress(address, port_number1);
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//Reading the message from the client
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
//Shut down with zero-length message
if(MessageFromClientDecodedFromUTF8.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
//creating message to server send from standard input
String newmessage = "";
try {
// input the message from standard input
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null && KeepRunning==true )
{
newmessage += line + " \n ";
}
}
catch ( Exception e ) {
System.out.println( e.getMessage() );
}
//Writing return message back to client
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Server.start();
}
}
Client file (DirectMessengerClient.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
boolean KeepRunning = true;
private static Socket socket;
//static String[] arguments;
//public static void main(String[] args)
//{
// arguments = args;
//}
public DirectMessengerClient()
{
//System.out.println("test.");
}
public void ClientRun(String[] args)
{
Thread Client = new Thread ()
{
public void run()
{
System.out.println("Client thread is now running");
try
{
System.out.println("Try block begins..");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
while(KeepRunning)
{
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n"); // <--- ADD THIS LINE
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
if(MessageFromServer.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Client.start();
}
}
Main function file (DirectMessengerCombined.java):
public class DirectMessengerCombined
{
public static void main(String[] args)
{
DirectMessengerClient Client1 = new DirectMessengerClient();
DirectMessengerServer Server1 = new DirectMessengerServer();
for (int i = 0; i < args.length; i++)
{
if(!args[0].equals("-l"))
{
Client1.ClientRun(args);
}
switch (args[0].charAt(0))
{
case '-':
if(args[0].equals("-l"))
{
Server1.ServerRun(args);
}
}
i=args.length + 20;
}
}
}
My question is: How do I change the way the strings are encoded or decoded in order to send strings to the other side or how to solve the null pointer exception error?
It is because you are trying to get the inputstream of a socket before it exists:-
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
These two lines should be the other way around. :)
EDIT: Looking further at your code, you are creating BufReader1 (which is causing the error) and then creating br in exactly the same way, i.e. both are a BufferedReader of the socket. You only need one; having two will probably cause problems for the readers.
server code :
public class server {
//private static ArrayList<user> t = new ArrayList<>();
public static Socket s = null;
public static ServerSocket ss = null;
public static void main(String[] args) {
try {
ss = new ServerSocket(1777);
while (true) {
System.out.println("waiting for connexion");
s = ss.accept();
System.out.println("connected with "+s.getRemoteSocketAddress());
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
String username = br.readLine();
int number = 0;
user us = new user(s,number,username);
//t.add(us);
pw.print(us);
//new service(s,username,number,t).start();
new service(s,us).start();
number++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
service class code :
public class service extends Thread {
private static Socket s;
private static String user;
private static int number ;
private ArrayList<user> locallist = new ArrayList<user>();
private static user us;
public service(Socket s,user u){
this.s = s;
this.us = u;
locallist.add(u);
}
#Override
public void run() {
int listsize = locallist.size();
user lastuser = locallist.get(listsize-1);
try {
while (true) {
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
System.out.println("last user : " + lastuser);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
client class code :
public class client {
public static void main(String[] args) {
try {
while (true) {
Socket s = new Socket("localhost",1777);
System.out.println("connected with localhost");
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
Scanner e = new Scanner(System.in);
System.out.println("enter you username to continue");
String username = e.next();
pw.println(username);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
the server output :
waiting for connexion
connected with /127.0.0.1:51899
waiting for connexion
connected with /127.0.0.1:51902
last user : username teste usernumber 0
last user : username teste usernumber 0
last user : username teste usernumber 0
basically infinit loop
the client output :
connected with localhost
enter you username to continue
teste
connected with localhost
enter you username to continue
my question is how can i stop the infinit loop and display the last connected/added member after each client connection
in the server class:
public static void main(String[] args) {
try {
ss = new ServerSocket(1777);
int number = 0; // <--- place the counter here not in the while
while (true) {
System.out.println("waiting for connexion");
s = ss.accept();
System.out.println("connected with "+s.getRemoteSocketAddress());
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
String username = br.readLine();
//int number = 0; // Not here ... you just set the counter always to 0
user us = new user(s,number,username);
pw.print(us);
new service(s,us).start();
number++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
in the service class:
#Override
public void run() {
int listsize = locallist.size();
user lastuser = locallist.get(listsize-1);
try {
// while(true) { // <--- should be removed
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
System.out.println("last user : " + lastuser);
// } <--- while-end
// <--- for later use?
} catch (Exception e) {
e.printStackTrace();
}
}
so that is the finished code ... you just had to remove the while in the service-class, move the declaration of the counter-variable "number" out of the while in the server-class.
If you want to use the while in the service-class later for communication between server and client you just have to place a while after you printed the user out.
I'm delving into sockets for the first time.
The point of the project is for the client to be able to get access to a contact list (CSV) in the server by writing "getall" and exit the program through just that command ("Exit").
The problem is that the client can only write the command and receive the list once and then the server doesn't respond to the client's input anymore.
Here is the socket code for the server and client respectively:
Server:
public class CatalogueServer extends CatalogueLoader {
ServerSocket serverSocket;
ArrayList<CatalogueEntry> catalogue;
public void startServer(int port, String catalogueFile) {
catalogue = loadLocalCatalogue(catalogueFile);
try {
serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
new Thread(
new Runnable() {
public void run() {
try {
InputStream inputStream = clientSocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader BR = new BufferedReader(inputStreamReader);
OutputStream outputStream = clientSocket.getOutputStream();
PrintWriter PW = new PrintWriter(outputStream);
String clientInput;
while ((clientInput = BR.readLine()) != null) {
System.out.println(clientInput);
if (clientInput.equals("getall")) {
System.out.println(printCatalogue(catalogue));
PW.println(printCatalogue(catalogue));
PW.flush();
break;
} else if (clientInput.equals("exit")) {
clientSocket.close();
BR.close();
PW.close();
break;
} else {
PW.flush();
break;
}
}
PW.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
).start();
}
} catch (Exception i) {
i.printStackTrace();
}
}
}
Client:
public class TestClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5253);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader BR = new BufferedReader(inputStreamReader);
while (true) {
String clientInput;
String serverFeedback;
PrintWriter PW = new PrintWriter(outputStream);
Scanner inputScan = new Scanner(System.in, "UTF-8");
clientInput = inputScan.nextLine();
PW.println(clientInput);
PW.flush();
while ((serverFeedback = BR.readLine()) != null) {
System.out.println(serverFeedback);
}
if (clientInput.equals("exit")) {
PW.close();
socket.close();
break;
}
PW.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
I have tried alternating the position and renewal of the readers and writers. But I'm uncertain of where exactly the problem starts.
When you do
while ((serverFeedback = BR.readLine()) != null) {
System.out.println(serverFeedback);
}
You are reading until you reach the end of the stream, i.e. until there is nothing left. As such there is nothing after this.
If you want to reuse the connection, you have to write the code which doesn't use this pattern and only reads until it should stop reading.