1

下面是有一个服务器接受多个客户端连接并响应的代码。服务器能够接收客户端的消息,但客户端没有接收服务器消息。我在服务器上使用了多线程概念。我还观察到,除了标有#### 的行之外,没有任何效果(甚至是 println 语句)。可能是那个客户端被阻止了..有什么想法吗?服务器代码:public static void main(String argv[]) throws Exception {

     ServerSocket welcomeSocket = new ServerSocket(10000);

     while(true)
     {

        Socket connectionSocket = welcomeSocket.accept(); 

        Thread t = new Thread(new acceptconnection(connectionSocket));
        t.start();}}


   class acceptconnection implements Runnable{
            BufferedReader inFromClient,inn;
                DataOutputStream ds;
             Socket clientsocket;
        //constructor
        acceptconnection (Socket socket) throws IOException{
        this.clientsocket = socket;
        inn = new BufferedReader (new InputStreamReader(System.in));
        inFromClient =new BufferedReader(new  InputStreamReader(clientsocket.getInputStream()));
        ds = new DataOutputStream(clientsocket.getOutputStream());

         public void run (){
         try {
        String clientSentence, inp;
         while(( clientSentence = inFromClient.readLine())!=null)
         {
               System.out.println("from client" + clientSentence);
               ds.writeBytes("hi from server");**// THIS DOES NOT WORK**
         }

    }


  Client code:

     public static void main(String argv[]) throws Exception
   {

  Socket clientSocket;
   while(true)
  {
   // clientSock
    clientSocket = new Socket("localhost", 10000);
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));

  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new    InputStreamReader(clientSocket.getInputStream()));

  System.out.println("Enter something:"); 
  sentence = inFromUser.readLine();  
  outToServer.writeBytes(sentence + '\n');// THIS WORKS - thats why server receives it

  **####** modifiedSentence = inFromServer.readLine();**// THIS DOES NOT WORK -client unable to receive** 

  System.out.println("FROM SERVER: " + modifiedSentence + "remote sock add: "+      clientSocket.getRemoteSocketAddress());
4

2 回答 2

1

您应该在服务器端刷新流

 ds.writeBytes("hello world".getBytes());
 ds.flush();
于 2012-09-18T19:53:49.110 回答
1

当您BufferedReader.readLine()在客户端中使用时,请确保在写出数据时使用换行符:

ds.writeBytes("hi from server\n"); 

而且,如前所述,记得冲洗...

ds.flush();
于 2012-09-18T20:00:17.223 回答