I'm trying to establish a simple tcp connection.The client-side let's the user input their name and the server-side answers with a welcome messages with the user's name. This goes on till "stop" is given as input.
When "stop" is given as input, the client stops and the server closes the connection to that client. Then the server waits for new incomming connections.
Client side:
public class Client {
public static void main(String[] args) {
InetAddress host = null;
Socket socket = null;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String name = "";
BufferedReader input = null;
PrintWriter output = null;
try {
host = InetAddress.getLocalHost();
socket = new Socket(host, 1024);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
}catch(UnknownHostException e) {
System.err.println(e);
}catch(SocketException e) {
System.err.println(e);
}catch(IOException e) {
System.err.println(e);
}
while (!(name.equals("stop"))) {
try {
System.out.println("Enter a name : ");
name = consoleInput.readLine();
output.println(name);
String msg = input.readLine();
System.out.println("Reply from server = " + msg);
}catch(IOException e) {
System.err.println(e);
}
}
try {
input.close();
output.close();
consoleInput.close();
socket.close();
}catch(IOException e) {
System.err.println(e);
}
}
}
Server side:
public class Server {
public static void main(String[] args) {
ServerSocket listen = null;
Socket client = null;
BufferedReader input = null;
PrintWriter output = null;
try {
listen = new ServerSocket(1024);
String name = "";
String rMess = "";
while(true) {
client = listen.accept();
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintWriter(client.getOutputStream(), true);
name = input.readLine();
if(!(name.equals("stop"))) {
rMess="Hello, "+ name;
output.println(rMess);
}else {
client.close();
input.close();
output.close();
}
}
}catch(UnknownHostException e) {
System.err.println(e);
}catch(SocketException e) {
System.err.println(e);
}catch(IOException e) {
System.err.println(e);
}
}
The first time around all goes well, but after I give in a second name the server does not send back a message.
Please login or Register to submit your answer