gpt4 book ai didi

java - 将套接字输出发送到 GUI 时出现问题

转载 作者:行者123 更新时间:2023-12-01 22:31:26 25 4
gpt4 key购买 nike

我编写了这个简单的多线程聊天室,我试图将客户端/服务器输出发送到 GUI 以将其显示在聊天室文本区域中,但我在以下行得到空指针异常:

output.write(line + "\n");

这是 GUI 的完整代码:

import java.awt.*;
import javax.swing.*;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.JButton;
import java.io.Writer;


public class GUI {

private JFrame frame;
private JButton btnSend, btnConnect;
private JTextArea txtChat;
private JTextField fldText, fldName;
private JList clientList;
private DefaultListModel listModel;
private JScrollPane sc, scClients;
private JPanel jpS2All, jpS2Client, jpS2Text;
private String Name;
private JLabel lblErr;
private Writer output;

public GUI(String Name, Writer output) {
this.Name = Name;
this.output = output;
}

public GUI() {

}


class handler implements ActionListener, MouseListener {

handler(String Name) {

}

handler() {

}

@Override
public void actionPerformed(ActionEvent e) {


clients(); //it seems this line made the error because it creates the
listModel.addElement(Name);//gui and sends the output to textSend actionlistener
//to display it in gui
//while the output is empty, right?
//is there any way to handle this?

}

@Override
public void mouseClicked(MouseEvent e) {
fldName.setText("");
}

@Override
public void mousePressed(MouseEvent e) {
}

@Override
public void mouseReleased(MouseEvent e) {
}

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

} //end of handler

class textSend implements ActionListener {

textSend(String Name, Writer output) {

}

@Override
public void actionPerformed(ActionEvent e) {
String line = fldText.getText();
try {
output.write(line + "\n"); // the null exception error shows the
output.flush(); // error source at this line!
} catch (IOException ioe) {
txtChat.append("Other party hung up!");
}
String contenet = Name + ":" + output;
txtChat.append(contenet);
fldText.setText("");
}

}//end of textSend

public void creatServer() {

frame = new JFrame("enter");
frame.setBounds(50, 50, 300, 200);
btnConnect = new JButton("connect");
lblErr = new JLabel();
lblErr.setText("");
frame.add(btnConnect, BorderLayout.EAST);
fldName = new JTextField();
fldName.setText("enter your name");
fldName.addMouseListener(new handler());

btnConnect.addActionListener(new handler(getName()));

frame.add(fldName, BorderLayout.CENTER);
frame.setVisible(true);

}


public void clients() { //to create the chatroom GUI
frame = new JFrame("friends");
frame.setBounds(100, 100, 400, 400);
jpS2All = new JPanel();
txtChat = new JTextArea();
txtChat.setRows(25);
txtChat.setColumns(25);
txtChat.setEditable(false);

sc = new JScrollPane(txtChat);
jpS2All.add(sc);
frame.add(jpS2All, BorderLayout.WEST);
jpS2Text = new JPanel();

////////////////////////
fldText = new JTextField();
fldText.setColumns(34);
fldText.setHorizontalAlignment(JTextField.RIGHT);
fldText.addActionListener(new textSend(getName(), output));
jpS2Text.add(fldText);
frame.add(jpS2Text, BorderLayout.SOUTH);

/////////
jpS2Client = new JPanel();

listModel = new DefaultListModel();
clientList = new JList(listModel);
clientList.setFixedCellHeight(14);
clientList.setFixedCellWidth(100);
scClients = new JScrollPane(clientList);

frame.add(jpS2Client.add(scClients), BorderLayout.EAST);
/////////
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();

}//end of clients

public String getName() {
Name = fldName.getText();
return Name;
}

public void appendText(final String message) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
txtChat.append(message);
}
});
}
}

服务器代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class server {

public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
while (true) {
Socket socket = serverSocket.accept();
ClientThread t = new ClientThread(socket);
t.start();
}
}

public static void main(String[] args) throws IOException {
server server = new server();
server.start();

}

class ClientThread extends Thread {

Socket socket;
InputStream sInput;
OutputStream sOutput;
GUI gui = new GUI();
String Name;

ClientThread(Socket socket) {
this.socket = socket;

}

@Override
public void run() {
try {
BufferedReader sInput
= new BufferedReader(new InputStreamReader(socket.getInputStream()));
Writer sOutput = new OutputStreamWriter(socket.getOutputStream());
Name = gui.getName();
gui = new GUI(Name, sOutput);

try {
String line;
while ((line = sInput.readLine()) != null) {
gui.appendText(line);
}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}

} catch (IOException e) {
}
}
}
}

客户端:

import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class client {

private Socket s;
private String Name;
private GUI gui;
private Writer output;
private BufferedReader input;

public void start() {

try {
s = new Socket("127.0.0.1", 1234);
} catch (IOException ex) {

}
try {
input = new BufferedReader(new InputStreamReader(s.getInputStream()));
output = new OutputStreamWriter(s.getOutputStream());
} catch (IOException eIO) {

}
Name = gui.getName();
new GUI(Name, output);
new ListenFromServer().start();

}

public static void main(String[] args) {
client cl = new client();
GUI gui = new GUI();
gui.creatServer();
}

class ListenFromServer extends Thread {

public void run() {
try {
String line;
while ((line = input.readLine()) != null) {
gui.appendText(line);
}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

}

我知道我的问题有点麻烦,但我真的很感激能帮助我解决这个问题!

最佳答案

我正在查看您的代码,很明显 outputnull当您尝试output.write(line + "\n");时因此我去寻找可能离开output的执行路径。未初始化。这就是调试非常方便的地方。

这是您的执行路径:

client 的主要方法中您创建一个新的 GUI然后调用gui.creatServer();

public static void main(String[] args) {
client cl = new client();
GUI gui = new GUI();
gui.creatServer();
}

输出尚未分配且仍为空

creatServer();方法你有这一行:

    fldName.addMouseListener(new handler());

其中actionPerformed方法handler调用clients();具有以下行的方法:

fldText.addActionListener(new textSend(getName(), output));

注意output 仍然为空

(现在你的 textSend 类在构造函数中甚至没有做任何事情,但除此之外,即使它做了,你仍然使用 output 类中的 GUI 变量)

你有actionPerformed textSend中的方法具有以下行的类:

output.write(line + "\n");

无需初始化output它仍然为空,这给你 NullPointer

请参阅What is a NullPointerException, and how do I fix it?正如评论中链接的@markspace。此外,你应该真正学习如何调试小程序。

请参阅以下链接:

http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ http://blogs.msdn.com/b/smallbasic/archive/2012/10/09/how-to-debug-small-basic-programs.aspx

此外,请考虑使用 Anonymous类来简化这些代码行,这也使代码更易于调试且更具可读性。

最后一个想法,记住使用标准 Naming Conventions对于您正在使用的语言。您的代码当前有很多不正确的小写类和一些大写方法/属性。

关于java - 将套接字输出发送到 GUI 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27659686/

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