1

我有一个服务器/客户端套接字连接,每一方都可以向另一方发送消息。必须开始聊天的客户。当双方(服务器和客户端)之一发送“退出”消息时,我想关闭连接。这是我的代码:

import java.io.*; 
import java.net.*; 
class TCPClient { 

    public static void main(String argv[]) throws Exception 
    { 
        String sentence; 
        String modifiedSentence; 
while(true){
        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);

        if(modifiedSentence.equals("quit\n")) clientSocket.close();

}
    }
}


import java.io.*; 
import java.net.*; 

class TCPServer { 

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

    BufferedReader inFromUser = 
          new BufferedReader(new InputStreamReader(System.in));

      ServerSocket welcomeSocket = new ServerSocket(6789); 

      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("FROM CLIENT: " + clientSentence);

           //capitalizedSentence = clientSentence.toUpperCase() + '\n';
           sentence = inFromUser.readLine();
           outToClient.writeBytes(sentence);
       }
   }
}

有什么帮助吗?:)

4

1 回答 1

1

你已经写了一行。为“退出”写另一个,并在读取和关闭()时检查此字符串。

如果您不了解程序在做什么,请使用调试器,这就是它的用途。

于 2013-09-17T22:17:30.817 回答