我已经把问题简化成如下例子:第一次用socket的getOutputStream时无异常 但把数据流close后 再用同样的方法获取数据流就报Socket is Closed的异常。请高人指点。 代码如下(注释掉的那块 就是出问题的地方):
Server端:
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server2 {
ServerSocket ss;
Socket st;
DataOutputStream dos;
public void start() {
try {
ss = new ServerSocket(8989);
st = ss.accept();
dos = new DataOutputStream(st.getOutputStream());
dos.writeInt(1);
dos.close();
// dos = new DataOutputStream(st.getOutputStream());
// dos.writeInt(2);
// dos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
dos = null;
}
}
public static void main(String args[]) {
new Server2().start();
}
}Client端:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client22 {
private Socket st;
private DataInputStream dis;
public void start() {
try {
st = new Socket("127.0.0.1",8989);
dis = new DataInputStream(st.getInputStream());
System.out.println(dis.readInt());
dis.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
dis = null;
}
}
public static void main(String[] args) {
new Client22().start();
}
}

解决方案 »

  1.   

    你的服务器端得有死循环啊,不死循环,方法结束,服务端的socket不就关闭了?
      

  2.   

    我知道你说的意思,当close掉后,在调用st.getOutputStream()时,就会有这样的判断if (isClosed())throw new SocketException("Socket is closed");我也不知道为什么要抛出“Socket is closed”,但原因就是dos.close();这句话, 改成这样就可以了:
    ss = new ServerSocket(8989); 
    st = ss.accept(); 
    dos = new DataOutputStream(st.getOutputStream()); 
    dos.writeInt(1); 
    dos = new DataOutputStream(st.getOutputStream()); 
    dos.writeInt(2); 
    dos.close(); 
      

  3.   

    问题的关键是你不能这样写,在outputstream关闭的时候,socket也就关闭了。