gpt4 book ai didi

java - 无法从多线程 Java 聊天室退出用户

转载 作者:行者123 更新时间:2023-12-02 09:44:50 25 4
gpt4 key购买 nike

我一直在关注有关创建使用多线程的基于 GUI 的聊天室的教程。我想添加一个关键字,例如“\EXIT”,这样当用户键入它时,他们将与聊天室断开连接,并向聊天室发送一条消息,表明用户已离开。例如:

本:嗨

凯蒂:嗨

:G2G

:退出

本已离开聊天室

到目前为止,我有这个:

服务器.java

//ChatServer.java

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.net.Socket;

public class ChatServer {

static ArrayList<String> userNames = new ArrayList<String>();

static ArrayList<PrintWriter> printWriters = new ArrayList<PrintWriter>();

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

System.out.println("Press 1 for Console or 2 for GUI");
System.out.println("Waiting for clients...");

ServerSocket ss = new ServerSocket(14001);

while (true){

Socket soc = ss.accept();
System.out.println("Connection established");

ConversationHandler handler = new ConversationHandler(soc);

handler.start();

}

}

}

class ConversationHandler extends Thread

{

Socket socket;
BufferedReader in;
PrintWriter out;
String name;
PrintWriter pw;
static FileWriter fw;
static BufferedWriter bw;

public ConversationHandler(Socket socket) throws IOException {

this.socket = socket;

fw = new FileWriter("C:\\Users\\Abhay\\Desktop\\ChatServer-Logs.txt",true);
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw,true);

}

public void run() {

try {

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

int count = 0;

while (true){

if(count > 0){

out.println("NAMEALREADYEXISTS");

}

else{

out.println("NAMEREQUIRED");

}

name = in.readLine();

if (name == null){

return;

}

if (!ChatServer.userNames.contains(name)){

ChatServer.userNames.add(name);

break;

}

count++;

}

out.println("NAMEACCEPTED"+name);
ChatServer.printWriters.add(out);

while (true){

String message = in.readLine();



if (message.equals("EXIT")) {

pw.println(name + " has disconnected from the chat");

System.out.println(name + " has disconnected from the chat");

ChatServer.userNames.remove(name);
}

pw.println(name + ": " + message);

for (PrintWriter writer : ChatServer.printWriters) {

writer.println(name + ": " + message);

}

}

}

catch (Exception e){

System.out.println(e);

}

}

}

Client.Java

//ChatClient.java

import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;



public class ChatClient {

static JFrame chatWindow = new JFrame("Chat Application");
static JTextArea chatArea = new JTextArea(22, 40);
static JTextField textField = new JTextField(40);
static JLabel blankLabel = new JLabel(" ");
static JButton sendButton = new JButton("Send");
static BufferedReader in;
static PrintWriter out;
static JLabel nameLabel = new JLabel(" ");

ChatClient() {

chatWindow.setLayout(new FlowLayout());
chatWindow.add(nameLabel);
chatWindow.add(new JScrollPane(chatArea));
chatWindow.add(blankLabel);
chatWindow.add(textField);
chatWindow.add(sendButton);
chatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chatWindow.setSize(475, 500);
chatWindow.setVisible(true);
textField.setEditable(false);
chatArea.setEditable(false);
sendButton.addActionListener(new Listener());
textField.addActionListener(new Listener());

}

void startChat() throws Exception {

String ipAddress = JOptionPane.showInputDialog(

chatWindow,

"Enter IP Address:",

"IP Address is Required!",

JOptionPane.PLAIN_MESSAGE);

Socket soc = new Socket(ipAddress, 14001);

in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
out = new PrintWriter(soc.getOutputStream(), true);

while (true){

String str = in.readLine();

if (str.equals("NAMEREQUIRED")){

String name = JOptionPane.showInputDialog(

chatWindow,

"Enter a unique name:",

"Name Required!!",

JOptionPane.PLAIN_MESSAGE);

out.println(name);

}

else if(str.equals("NAMEALREADYEXISTS")){

String name = JOptionPane.showInputDialog(

chatWindow,

"Enter another name:",

"Name Already Exits!!",

JOptionPane.WARNING_MESSAGE);

out.println(name);

}

else if (str.startsWith("NAMEACCEPTED")){

textField.setEditable(true);

nameLabel.setText("You are logged in as: "+str.substring(12));

}

else{

chatArea.append(str + "\n");

}

}

}

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

ChatClient client = new ChatClient();

client.startChat();

}

}

class Listener implements ActionListener

{
@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

ChatClient.out.println(ChatClient.textField.getText());

ChatClient.textField.setText("");

}

}

正如你所看到的,在Server.java中,我使用了这个IF语句。

if (message.equals("EXIT")) {

pw.println(name + " has disconnected from the chat");

System.out.println(name + " has disconnected from the chat");

ChatServer.userNames.remove(name);
}

但是,当我运行该程序时,用户不会从聊天中删除。感谢任何帮助提示!

最佳答案

它没有在 GUI 上打印,因为您使用了错误的 PrintWriter

out 是打印到 GUI 的内容pw 从我所看到的内容打印到文件/控制台。

尝试

out.println(name + "已与聊天断开连接");

此外,为了使用户退出聊天并关闭聊天,您应该使用 try{..} catch{..} finally{..} 关闭服务器端的套接字连接 code> 用于输入流、输出流和套接字,然后您可以在客户端检测并关闭客户端 GUI。

关于java - 无法从多线程 Java 聊天室退出用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741571/

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