先运行B.main,再运行A.main,先运行B的main,然后由于B有accepte的执行,所以B那块先阻塞,然后点击执行A.main的时候会执行A的socket连接,然后B监听到了之后立即写入,此时A和B是两个进程再运行,所以如果A先把Socket关闭时,B再通过Socket写入数据就会导致 j a v a . n e t . S o c k e t E x c e p t i o n : B r o k e n p i p e ( W r i t e f a i l e d ) java.net.SocketException: Broken pipe (Write failed) java.net.SocketException:Brokenpipe(Writefailed),解决办法就是防止一端关闭Socket后另外一端仍然通过Socket写入数据!!!!
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) {
}
}
class A extends Thread{
Socket s ;
/**
* 客户端
* @throws IOException
* @throws ClassNotFoundException
*/
public A() throws IOException ,ClassNotFoundException{
s=new Socket("127.0.0.1", 9999);
s.close();
}
@Override
public void run() {
try
{
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
Integer i = (Integer)ois.readObject();
System.out.println(i);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)throws IOException,ClassNotFoundException {
new A().start();
}
}
class B extends Thread{
ServerSocket ss ;
Socket s ;
/**
* 服务器
* @throws IOException
*/
B()throws IOException{
ss = new ServerSocket(9999);
}
@Override
public void run() {
try
{
s = ss.accept();
System.out.println("Receive Successfully!!");
Integer i = new Integer(1);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject(i);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException,ClassNotFoundException{
new B().start();
}
}
点击此处查看参考的原文连接