马士兵的在线聊天项目的问题
自学java不容易啊,先感慨一下。
好,说正事。
跟着视频做马士兵的在线聊天项目,编译,运行都没有问题,但是在控制台那里总是接收不到输入的信息。我把跟着视频的源代码倒入项目控制台也是没有输出。有没有做过这个项目的同学,帮忙看一下,不甚感激。
源代码如下:
ChatClient.java:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
System.out.println("connected!");
} catch (
UnknownHostException e) {
e.printStackTrace();
} catch (
IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
taContent.setText(str);
tfTxt.setText("");
try {
//System.out.println(s);
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
ChatServer.java:
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
boolean started = false;
try {
ServerSocket ss = new ServerSocket(8888);
started = true;
while(started) {
boolean bConnected = false;
Socket s = ss.accept();
System.out.println("a client connected!");
bConnected = true;
DataInputStream dis = new DataInputStream(s.getInputStream());
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
}
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}