-->

Java Socket client & server [duplicate]

2019-03-06 15:14发布

问题:

This question is an exact duplicate of:

  • Java socket , client and server [closed] 1 answer

I tried the following code to send list of files and directories, from server to client. the server is receiving from client but i don't know whether server is not sending back the result or client is not accepting it.

Server side:

package without.thread;


import java.io.BufferedOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import static java.rmi.Naming.list;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.logging.Level;
import java.util.logging.Logger;


public class SerTest {
  public static int reads,red;  
    public static void main(String[] args) 
    { 

          try
                  {
                      System.out.print("i m ready, call my client");
            ServerSocket serverSocket = new ServerSocket(18789);
                       while(true){ 
            Socket clientSocket = serverSocket.accept();
                        System.out.println(clientSocket+"1");
                       // outk=new PrintWriter(clientSocket.getOutputStream(),true); 

                         BufferedReader bufferedReader;
       bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                }

回答1:

From what I can see you do readLine() on the client, while doing outqw.write() on the server. There is no end of line character in the string sent from server, so the client will never be able to finish the readLine. Do the outqw.println() or add "\n" to the end of whatever you're sending. That being said, it's very hard to navigate unformatted code with bunch of commented out stuff so the problem might be something else.



回答2:

Try manualy flushing the stream when sending something to the server/client.