Android TCP Client/Server not passing messages properly (Only first received) - java

I have created two android applications, a client and a server, utilizing TCP to communicate across devices. On the server, I have this code to listen for TCP communication:
private class StartServer implements Runnable {
public void run() {
getState(); // This just refreshes the server state
try {
serverSocket = new ServerSocket(5000);
appendLog("Server successfully listening ["+getLocalIpAddress() + ":5000]"); //appendLog function just uses runOnUiThread() to update the log textview
} catch (IOException e) {
appendLog("Could not listen on port: 5000");
//System.exit(-1);
}
BufferedReader in = null;
BufferedWriter out = null;
String input = null;
try {
clientSocket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
while (serverState) { //variable set by our getState() function
input = in.readLine();
appendLog("Received: " + input);
this.gotMessage(out, input);
}
in.close();
out.close();
} catch (IOException e) {
//appendLog(e.toString());
appendLog("Accept failed: 5000");
//System.exit(-1);
}
}
Which calls this function to actually parse the recieved messages:
private void gotMessage(BufferedWriter output, String msg) {
if (msg != null) {
String sString = msg;
int to_do = 0;
if (msg.matches("^(?i)(exit|quit|close)$")) {
appendLog("Exiting");
sString = "Goodbye";
to_do=1;
} else if (msg.matches("^(?i)(launch|run|open)\\s(.+)")) {
appendLog("Launching application");
sString = "Launching application";
} else if (msg.matches("^(?i)(turn off|server off|deactivate)$")) {
appendLog("Turning off server due to remote command.");
sString = "Turning off...";
to_do=2;
} else if (msg.matches("^(?i)(restart|reboot)$")) {
appendLog("Resetting server");
sString = "Rebooting now...";
to_do=3;
}
try {
output.write("S: " + sString);
output.newLine();
output.flush();
} catch (IOException e) {
appendLog("Cannot parse message");
}
switch(to_do) {
case 0:
break;
case 1:
System.exit(0);
break;
case 2:
serverOff();
break;
case 3:
serverOff();
serverOn();
break;
default:
break;
}
}
}
}
The thread itself for the server is started using Thread t = new Thread(new StartServer()); t.start(). And to the best of my knowledge, this works fine. I can open up a terminal and telnet to the IP and port, and pass communication back and forth without error. But when I try to do the same from the client code below. I only get the first message, and anything else I pass in just dissappears into the void.
public void sendToServer(View v) {
try {
String ip = ((TextView)findViewById(R.id.ip_box)).getText().toString(); //User entered IP address
String to_send = ((EditText)findViewById(R.id.send_to_server)).getText().toString(); //User entered text to send
this.s = new Socket(ip, 5000);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
appendLog("Sending: " + to_send);
out.write(to_send);
out.newLine();
out.close();
} catch (Exception e) {
Log.d("error", e.toString());
}
}

Do you have line-end character in your to_send string? if no, just add out.newLine() to your client code:
appendLog("Sending: " + to_send);
out.write(to_send);
out.newLine();
You server code should look like this to support multiple clients:
// main server loop
while (serverIsActive) {
clientSocket = serverSocket.accept();
// spawn new thread for each client
ClientThread ct = new ClientThread(clientSocket);
ct.start();
}
ClientThread should work with client socket and have its own loop for reading lines. It should stop as soon as client closes socket:
class ClientThread {
...
public void run() {
....
while ((inputLine = in.readLine()) != null) {
// process client message
}
in.close();
}
}

Related

Java - How do I loop to read the InputStream until the user makes an input to continue?

I have a multithreaded client-server system which works back and forth with the client communicating first and the server replying.
However, for two specific clients, I need them to constantly check if there is data held in the input stream before proceeding when the user makes an input.
The program is a car park management system. When the car park is full(0 spaces available) and a car arrives at an entrance client, the system forms a queue of clients waiting to grant entry. When a car leaves the car park, the first client in the queue is removed and added to a BlockingQueue for that specific entrance client. I have created a direct output output stream for each of the entrance clients. So when a BlockingQueue is not empty, data is taken from this queue and output is sent to the stream of that specific client.
However, the problem is - the entrance client which was queued should automatically read its InputStream and print the data to grant access, but instead it causes an error and crashes. I think what is happening is that when the system first starts, the is the client is stuck waiting to read data which initially doesn't exist because it would require some sort of input at the first stage, causing an error.
How do I fix this so that the client reads and prints the input stream(whether it be specific data such as contains the word "queue") IF there is data available else to continue IF the user makes an input.
I hope this makes sense, I tried to make it as clear as possible.
Server class:
public class Server {
public static void main(String[] args) throws IOException {
//Create the shared objects in the global scope...
int groundFloor = 0; //SET TO 0 FOR TESTING
int firstFloor = 0;
SharedState SharedStateObject = new SharedState(groundFloor,firstFloor);
//Sets up the server socket on port 4444
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(4444);
System.out.println("Car Park Server started." + "\n");
}
catch (IOException e) {
System.err.println("Could not start server on specified port.");
System.exit(-1);
}
//Got to do this in the correct order with only four clients!
ServerThread GroundFloorEntrance = new ServerThread(serverSocket.accept(), "GroundFloorEntrance", SharedStateObject);
ServerThread FirstFloorEntrance = new ServerThread(serverSocket.accept(), "FirstFloorEntrance", SharedStateObject);
ServerThread GroundFloorExit1 = new ServerThread(serverSocket.accept(), "GroundFloorExit1", SharedStateObject);
ServerThread GroundFloorExit2 = new ServerThread(serverSocket.accept(), "GroundFloorExit2", SharedStateObject);
GroundFloorEntrance.start();
FirstFloorEntrance.start();
GroundFloorExit1.start();
GroundFloorExit2.start();
serverSocket.close();
//Loop for granting queued clients access
while(true)
{
BlockingQueue<String> queuedGroundAccess = SharedStateObject.getQueuedGround();
BlockingQueue<String> queuedFirstAccess = SharedStateObject.getQueuedFirst();
if(!queuedGroundAccess.isEmpty())
{
Socket clientSocket = GroundFloorEntrance.clientSocket();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
try
{
out.println(queuedGroundAccess.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(!queuedFirstAccess.isEmpty())
{
Socket clientSocket = FirstFloorEntrance.clientSocket();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
try
{
out.println(queuedFirstAccess.take());
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
Client
public class GroundFloorEntrance {
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
// Set up the socket, in and out variables
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
int port = 4444;
String serverName = "localhost";
String clientID = "Ground Floor Entrance";
try {
clientSocket = new Socket(serverName, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: "+ port);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer = null;
String fromUser = null;
System.out.println("Initialised " + clientID + " client and IO connections");
//I THINK THE ISSUE IN THE FOLLOWING STRUCTURE:
while (true) {
fromServer = in.readLine();
if(fromServer != null && fromServer.contains("Queue: "))
{
System.out.println(fromServer);
}
fromUser = stdIn.readLine();
if (fromUser != null) {
out.println(fromUser);
}
fromServer = in.readLine();
System.out.println(fromServer);
}
}
}
A problem is in this loop. When you write fromServer = in.readLine(); it stop execution of your program and waits for data to be entered from server.
while (true) {
fromServer = in.readLine();
if(fromServer != null && fromServer.contains("Queue: "))
{
System.out.println(fromServer);
}
fromUser = stdIn.readLine();
if (fromUser != null) {
out.println(fromUser);
}
fromServer = in.readLine();
System.out.println(fromServer);
}
What you can do with that? You should read data from server in another thread to prevent blocking main thread while waiting for data. Like that:
new Thread(new MyRunnable(fromServer)).start();
And MyRunnable will look like this:
public class MyRunnable implements Runnable {
private Scanner scanner;
public MyRunnable(Scanner scanner) {
this.scanner = scanner;
}
#Override
public void run() {
while (true) {
if (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
}
If you will have some questions, please ask.

Calling a java client in an android application

I have a client which can send some information to a server via TCP :
public class IR {
private String host; //server IP address indicated here, I deleted it for posting here
private int port = 6789;
private String sentence;
private String reply;
public IR(String type) {
try {
Socket clientSocket = new Socket(host,port); //IP du server ("localhost" pour un server local) et port utilisé
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Gson gson = new GsonBuilder().create();
FileReader file = new FileReader("data/userInfo.json");
String json = "";
int i = 0;
while ((i = file.read()) != -1)
json += (char)i;
User user = gson.fromJson(json, User.class);
String user_id = user.getID();
int bus_id = user.getBusID();
sentence = "alerte " + type + " " + user_id + " " + bus_id;
System.out.println("SENTENCE: " + sentence);
outToServer.writeBytes(sentence + '\n');
reply = inFromServer.readLine();
System.out.println("ANSWER: " + reply);
clientSocket.close();
}
catch (Exception io) {
System.out.println("Connection refusée: arrêt");
}
}
}
I am calling this in my android application : I have a button which use this method when I'm clicking on it :
public void signalerComplet(View view)
{
client = new IR("complet");
Toast.makeText(this, "envoyé", Toast.LENGTH_SHORT).show();
}
But my server doesn't get anything .
Though, I ma sure that my client works when I'm using it not in my android application .
Could somebody say to me what I am missing here ?
EDIT after getting Hector's help : the server gets my "bloubloubloub" but I get an android.os.NetworkOnMainThreadException on the "int size = in.read(data);" ...
private Socket socket;
public void signalerComplet(View view)
{
PrintWriter out = null;
InputStream in=null;
byte[] data = new byte[5120];
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
}
catch (IOException e) {
e.printStackTrace();
}
out.println("bloubloubloub" + '\n');
out.flush();
try {
in = socket.getInputStream();
int size = in.read(data);
}
catch (IOException e) {
e.printStackTrace();
}
Log.e("data from server", data.toString());
}
type.equals(null) will always be false as if the variable type actually holds a null value it will throw a NullPointerException as there is no method equals for the null value. Therefore the if body will never execute.
The correct way to match if a variable is null is by the == operator.
if (type == null) {
// do this
} else {
// do that
}
equals() on a String should be used to compare against another String.
In Android you can't just put all this code in the onCreate method (for example) and run it, because you can't start a proccess that blocks the main thread, in this case Socket clientSocket = new Socket(host,port); will block the main thread and you app will crashes. You need do this tcp communication using threads. Please try this code and follow this algorithm:
Create this inner class, this will excecute the socket connection using threads:
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new Socket(ipServer, portServer);
} catch (UnknownHostException e1) {
threadMsg("Connection fails");
} catch (IOException e1) {
threadMsg("Connection fails");
}
}
}
In onCreate Method call this
new Thread(new ClientThread()).start();
And in you send button should put something like this:
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
e.printStackTrace();
}
out.println(messageToServer);
out.flush();
And this should send the string to server socket. Also you need add some basic validations.
EDIT: To get data from server, add this code in a new onClick button method:
byte[] data = new byte[5120];
try {
in = socket.getInputStream();
int size = in.read(data);
// see the received data from server in you LogCat
Log.e("data from server", data.toString());
} catch (Exception e) {
e.printStackTrace();
}
Hope it helps.
When you do:
client = new IR("complet");
You will fall at the else statement in your IR constructor which does nothing despite to close connection.
Here is what I've done . Thanks again to Hector for his help . It works great . Anything which could be "magnified" would be appreciated . :)
public class SignalerProblemeActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signaler_probleme);
}
public void signalerComplet(View view)
{
new Thread(new CompletThread()).start();
Toast.makeText(this, "Signalement de bus complet envoyé", Toast.LENGTH_SHORT).show();
}
class CompletThread implements Runnable {
#Override
public void run() {
Socket socket=null;
User u = new User("momo",12);
String sentence="alerte complet "+u.getID()+u.getBusID();
try {
//CREATION SOCKET
socket=new Socket("123.456.789.10",6789);
//SENDING
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(sentence);
//GETTING
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String mstr=br.readLine();
Log.e("CLIENT",mstr);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch(Exception e)
{
Log.e("CLIENT",e.toString());
}
}
}
}

Multithreading with client server program

I am trying to implement multi threading with a client/server program I have been working on. I need to allow multiple clients to connect to the server at the same time. I currently have 4 classes: a Client, a Server, a Protocol and a Worker to handle the threads. The following code is what I have for those classes:
SocketServer Class:
public class SocketServer {
public static void main(String[] args) throws IOException {
int portNumber = 9987;
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
Thread thread = new Thread(new ClientWorker(clientSocket));
thread.start(); //start thread
String inputLine, outputLine;
// Initiate conversation with client
Protocol prot = new Protocol();
outputLine = prot.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = prot.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("quit"))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
SocketClient Class:
public class SocketClient {
public static void main(String[] args) throws IOException
{
String hostName = "localhost";
int portNumber = 9987;
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("quit"))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Protocol Class:
public class Protocol {
private static final int waiting = 0;
private static final int sentPrompt = 1;
private int status = waiting;
public String processInput(String theInput) {
String theOutput = null;
if (status == waiting) {
theOutput = "Please enter what you would like to retrieve: 'customer' or 'product' ";
status = sentPrompt;
}
else if ( status == sentPrompt ) {
if ( theInput.equalsIgnoreCase("product")) {
File f = new File("product.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current product entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("customer")) {
File f = new File("customer.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current customer entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("quit")) {
return "quit";
}
else {
return "quit";
}
}
return theOutput;
}
}
The ClientWorker Class:
public class ClientWorker implements Runnable {
private final Socket client;
public ClientWorker( Socket client ) {
this.client = client;
}
#Override
public void run() {
String line;
BufferedReader in = null;
PrintWriter out = null;
try {
System.out.println("Thread started with name:"+Thread.currentThread().getName());
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while (true) {
try {
System.out.println("Thread running with name:"+Thread.currentThread().getName());
line = in.readLine();
//Send data back to client
out.println(line);
//Append data to text area
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
When I run the server and client, everything works fine as expected. Then when I try to run another client, it just hangs there and does not prompt the client to give a response. Any insight into what I am missing is greatly appreciated!
Your server code should address implement below functionalities.
Keep accepting socket from ServerSocket in a while loop
Create new thread after accept() call by passing client socket i.e Socket
Do IO processing in client socket thread e.g ClientWorker in your case.
Have a look at this article
Your code should be
ServerSocket serverSocket = new ServerSocket(portNumber);
while(true){
try{
Socket clientSocket = serverSocket.accept();
Thread thread = new ClientWorker(clientSocket);
thread.start(); //start thread
}catch(Exception err){
err.printStackTrace();
}
}
How many times does serverSocket.accept() get called?
Once.
That's how many clients it will handle.
Subsequent clients trying to contact will not have anybody listening to receive them.
To handle more clients, you need to call serverSocket.accept() in a loop.

Production ready Socket server in Java

There are many tutorials where explains about socket server/client sides, but all them are very trivial. Is there any tutorial for production ready code? I'm new in sockets. There is a client, that sends strings to server. I must create the server side. in server side I read string from client and after some manipulation saves them in db. I must response to client only IF I get string like "Error" for example. and if there are no any daya from client in 30 secs, I must close client connection, but server side must works. this is my test Client side:
public class ClientSideSocket2 {
public static void main(String[] args) {
String serverName = "localhost";
int port = 5555;
String line = "";
Socket client = null;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
PrintWriter toServer = new PrintWriter(client.getOutputStream(), true);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
List<String> messages = new ArrayList<>();
for (int i = 0; i < 6; i++) {
messages.add("Message " + i+1);
}
messages.add("abc");
for (int i = 0; i < messages.size(); i++) {
toServer.println(messages.get(i));
if ((line = fromServer.readLine()) != null) {
System.out.println("Responce from server: " + line);
}
}
toServer.close();
fromServer.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
and my server side:
public class TRSServerInterface implements Runnable {
private ServerSocket serverSocket = null;
private Socket socket = null;
boolean runner = true;
String message = "";
public TRSServerInterface() {}
#Override
public void run() { // default run method of Thread class and Runnable interface
try {
int serverPort = 5555;
ServerSocket serverSocket = new ServerSocket(serverPort);
while(true) {
System.out.println("Waiting for connection...");
socket = serverSocket.accept();
System.out.println("Connected to " + socket.getRemoteSocketAddress());
//get the input and output streams
PrintWriter toClient = new PrintWriter(socket.getOutputStream(), true);
BufferedReader fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
do {
message = fromClient.readLine();
System.out.println("From client > " + message);
if (message.equals("abc")) {
toClient.println("Message from server");
}
else {
toClient.println("");
}
} while (!message.equals(""));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// try {
// objectOut.close();
// objectIn.close();
// socket.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
}
is my solution corrent and how I can close connection with client if there are no any data in 30 secs.
There are several production ready frameworks that should be used instead of rolling your own. Socket timeouts can be used to control how long different operations are allowed to take before an exception is thrown.

A simple java client server program

So I did this client server program in java for my college mini project. Note that this is just a small module of a big project I'm working on. I need a string to be sent from the client to the server. The server will return back the string as it is back to the client. (The code will be modified later such that the string is processed before sending back). The client will send a string whenever needed to the server. Thus it means it is compulsory for the server to be running for indefinite time.
The problem I face here is that my server works perfectly only for the first time when the client sends a string. If I run the client the second time with a different string, I get back the same string I sent to the server previously!
Here is my server program:
public class Server {
public static boolean x = true;
public static String reply;
public static void main(String a[]) throws Exception {
System.out.println("Entered server console..");
Socket echoSocket = null;
ServerSocket serverSocket = null;
PrintWriter out = null;
BufferedReader in = null;
System.out.println("Initializing Connection..");
boolean runFlag = true;
try {
serverSocket = new ServerSocket(77);
while (runFlag) {
echoSocket = serverSocket.accept();
out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
while (x) {
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
reply = in.readLine();
if (reply != null) {
x = false;
}
}
System.out.println("received: " + reply);
out.println(reply);
System.out.println("sent back: " + reply);
stdIn.close();
}
} catch (Exception e) {
System.out.println("Exception in starting server: " + e.getMessage());
} finally {
out.close();
in.close();
echoSocket.close();
}
}
}
Here is my Client program:
public class Client {
public static String reply,temp;
public static boolean x=true;
public Client()
{
temp="lala";
}
public Client(String t)
{
temp=t;
}
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 77);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
temp="lala"; //this is the string to be sent
out.println(temp);
while (x) {
reply= in.readLine();
if(reply!=null)
{
x=false;
}
}
System.out.println("reply: "+reply);
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
Can anyone help me find what the problem here is?
while (x) {
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
reply = in.readLine();
if (reply != null) {
x = false;
}
}
Your server enters this loop the first time a client connects, and it sets the reply String to some input from the client. However, it never enters this loop again, as x's value never changes back to true.
When you accept a request, the x will be set false and never become true.
Please initial the x when you enter the loop.
What's more,if you use a socket between client and server, please move the
echoSocket = serverSocket.accept();
out of the first loop.And you can use echoSocket to communicate.Then you will
keep the long connection.

Categories