我有一个服务器/客户端套接字连接,每一方都可以向另一方发送消息。必须开始聊天的客户。当双方(服务器和客户端)之一发送“退出”消息时,我想关闭连接。这是我的代码:
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);
}
}
}
有什么帮助吗?:)