我正在使用Java Swing制作聊天室程序。
在客户端,我看到并没有从服务器端读取消息。
客户端的writeUTF()
方法非常好,我在服务器端检查了readUTF
和writeUTF
,也非常好。
我认为问题在于在客户端充当"接收方"的代码。
在Thread的run()
方法中,DataInputStream
的实例dis
具有连续空值。
我太困惑了。。请给我一些帮助。
下面是我的客户&服务器代码。
谢谢!
客户端代码
RoomBackground.java
public class RoomBackground {
private static String socket_server = "127.0.0.1";
private static Socket chatSocket;
private static DataOutputStream dos;
private static DataInputStream dis;
private ChatReceiver chatReceiver;
public Socket getChatSocket() {
return chatSocket;
}
public static DataOutputStream getDos() {
return dos;
}
public RoomBackground() throws IOException {
chatSocket = new Socket(socket_server, 7777);
chatReceiver = new ChatReceiver();
chatReceiver.start();
dos = new DataOutputStream(chatSocket.getOutputStream());
dis = new DataInputStream(chatSocket.getInputStream());
dos.writeUTF(User.getUser().getUsername());
dos.flush();
}
class ChatReceiver extends Thread {
@Override
public void run(){
try {
# PROBLEM CODE..... Allways "dis is null"
System.out.println("dis is " + dis);
# This line never executed.
while(dis != null) {
# some codes.....
}
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.toString());
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
RoomFrame.java
public class RoomFrame extends JFrame{
private RoomBackground roomBackground;
public RoomFrame(int roomId) throws IOException {
chatField.addActionListener(new ActionListener() {
roomBackground = new RoomBackground();
@Override
public void actionPerformed(ActionEvent e) {
String msg = chatField.getText() + "n";
try {
RoomBackground.getDos().writeUTF(msg);
# It works.
System.out.println("sent msg is " + msg);
} catch (IOException e1) {
e1.printStackTrace();
}
chatField.setText("");
}
});
}
}
现在是服务器代码
服务器后台.java
public class ChatReceiver extends Thread {
private DataInputStream in;
private DataOutputStream out;
public ChatReceiver(Socket chatSocket) throws IOException {
out = new DataOutputStream(chatSocket.getOutputStream());
in = new DataInputStream(chatSocket.getInputStream());
nick = in.readUTF();
addChatClient(nick, out);
}
@Override
public void run() {
try {
while(in!=null) {
chatMsg = in.readUTF();
# It works !
System.out.println("before send" + chatMsg);
sendMsg(chatMsg);
# It works too!
System.out.println("after send" + chatMsg);
}
}catch (IOException e) {
removeChatClient(nick);
}
}
}
当您在RoomBackground
中启动ChatReceiver
线程时,dis
对象尚未初始化,这就是为什么它是null
。一种解决方案可以是初始化ChatReceiver
构造函数中的dis
变量。