Reputation: 689
I have this code and for some reason it stucks at readline() line at servers end always waiting from client but client on the other end sends the data.
Both the server and client's code is available below.
import java.io.*;
import java.net.*;
public class TCPServer {
public static final int SERVER_PORT = 6789;
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(SERVER_PORT);
while (true) {
Socket connectSocket = welcomeSocket.accept();
InputStream sin = connectSocket.getInputStream();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(sin));
PrintWriter outToClient = new PrintWriter(connectSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + "\r\n";
outToClient.print(capitalizedSentence);
}
}
}
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws Exception {
String hostName = "localhost";
int port = 6789;
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket(hostName, port);
PrintWriter outToServer = null;
clientSocket.getOutputStream();
BufferedReader inFromServer = null;
inFromServer=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.print(sentence + "\r\n");
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " +modifiedSentence);
clientSocket.close();
}
}
Upvotes: 0
Views: 465
Reputation: 20159
After fixing your syntax errors around outToServer
, I think the problem lies in the way you're using PrintWriter
around the output stream on the client's side. From the documentation:
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.
Since you're using print
with a manually appended new line, the message is never flushed to the socket's output stream. I believe you can fix this by using println
instead:
outToServer.println(sentence);
Even better would be to use DataInputStream
and DataOutputStream
instead of BufferedReader
and PrintWriter
, as those are better suited for sending and receiving arbitrary data over a socket stream.
Upvotes: 1