日期:2014-05-20  浏览次数:20775 次

小弟新手写的聊天软件,为什么聊天内容无法在服务端显示?
这是ChatClient:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatClient extends Frame {
Socket s = null;
TextField tf = new TextField();
TextArea ta = new TextArea();

public static void main(String[] args) {
new ChatClient().launchFrame();
}

public void launchFrame() {
setBounds(300, 300, 200, 400);
add(tf, BorderLayout.SOUTH);
add(ta, BorderLayout.NORTH);
this.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {
System.exit(0);
}

} );
pack();
tf.addActionListener(new TFListener());
setVisible(true);
connect();
}

public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
System.out.println("链接成功!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

private class TFListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
String str = tf.getText().trim();
ta.setText(str);
tf.setText("");
try {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
dos.flush();
dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}

}



}

  运行了之后在输入框里面输入的字无法在服务端显示!why? 哪里错了?我自己查了几遍了,没发现错误!!!
下面是服务器代码:

import java.io.*;
import java.net.*;

public class ChatServer {

public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888);
while(true) {
Socket s = ss.accept();
System.out.println("亲~ 连接成功了吗?");
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
System.out.println(str);
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}


}

}


------解决方案--------------------
朋友,我测试了你的程序,运行是正常的。我只是最初测试时我的8888端口被占用而出现异常,换个端口就能够正常运行。