I found this TCP server online, I want to modify it a little bit to return different message than was typed in the client. It doesn’t work as I want; the else {} works “like a charm” but the first if doesn’t – the client is still waiting for input.
server.java
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
String test="hey";
String tempus="tster";
if(clientSentence.contains(test)==true){
System.out.println(tempus);
outToClient.writeBytes(tempus);
}
else{
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
client.java
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
A common mistake when read/writing to files/socket is to mix and match text with binary and get horribly confused. You have used both.
You need to use text or binary, it appears you want to use text. e.g. BufferedReader and PrintWriter. (note: PrintWriter silently consumes exceptions in the underlying stream)