gpt4 book ai didi

java - java中的服务器/客户端聊天套接字

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:56 24 4
gpt4 key购买 nike

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

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

有什么帮助吗? :)

最佳答案

您已经写了一行。再写一个“quit”,并在读取和 close() 时检查该字符串。

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

关于java - java中的服务器/客户端聊天套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18860714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com