简体   繁体   中英

TCP Client/Server

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.

Server Code

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);
    }
  }
}

Client Code

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(); 
  } 
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM