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

运行后出现:java.net.SocketException: Socket is closed;求教
java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.IOException;
import java.io.*;
public class ChatClient extends Frame{
Socket ss = null;
  TextField tf=new TextField();
  TextArea ta=new TextArea();
public static void main(String[] args) {
new ChatClient().laFrame();
}
public void laFrame(){
this.setLocation(500,300);
this.setSize(500,400);
add(tf,BorderLayout.SOUTH);
add(ta,BorderLayout.NORTH);
pack();
setVisible(true);
connect();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
tf.addActionListener(new TFlistener());
}
public void connect(){
try {
ss= new Socket("127.0.0.1",8091);
System.out.print("已经成功连接服务器!!");
} catch (UnknownHostException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
private class TFlistener implements ActionListener{
public void actionPerformed(ActionEvent event){
//String str=tf.getText().trim();
//ta.setText(str);
  String s = tf.getText().trim() + "\n";
  ta.append(s);


tf.setText("");
try {
DataOutputStream dos= new DataOutputStream(ss.getOutputStream());
dos.writeUTF(s);
dos.flush();
dos.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
  

}
}
运行后出现:java.net.SocketException: Socket is closed;
服务器端代码是:import java.io.IOException;
import java.net.*;
import java.io.*;
public class ChatServer {


public static void main(String[] args) {
try {
System.out.print("服务器端启动成功!!");
ServerSocket s= new ServerSocket(8091);
while(true){
Socket ss=s.accept();
System.out.print("客户端已连接成功!!");
DataInputStream dis=new DataInputStream(ss.getInputStream());
String str=dis.readUTF();
System.out.println(str);
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}

}

}
我是新手 谢谢赐教!

------解决方案--------------------
服务器端最后为啥要close?