通过套接字发送对象(Send object via socket)

2019-10-21 06:00发布

我想通过套接字发送x对象,但是当我运行这段代码我得到空话。 它是停在new ObjectInputStream(socket.getInputStream())并没有做任何别的事情。

服务器类:

public class Server {
private static final int PORT = 9001;
ServerSocket listener;
private Handler h[] = new Handler[5];
private int clientCount = 0;
public Server() throws Exception{
    System.out.println("The server is running.");
    listener = new ServerSocket(PORT);
    run();
}
public void run(){
    while (true) {
        try {
            addClient(listener.accept());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  private void addClient(Socket socket) throws Exception{
    h[clientCount] = new Handler(this, socket,clientCount);
    h[clientCount].open(); 
    clientCount++;

}
public static void main(String[] args) throws Exception {
    Server s = new Server();

}
}

Handler类// handle类:

public class Handler extends Thread {
private Server  server;
private Socket socket;
private int ID = -1;
private ObjectInputStream obIn = null;
private ObjectOutputStream obOut = null;
public Handler(Server _server, Socket _socket, int i){
    super();
      server = _server;
      socket = _socket;
      ID     = i;
}
 public void open() 
   {  
      try {
          obIn = new ObjectInputStream(socket.getInputStream());
      obOut = new ObjectOutputStream(socket.getOutputStream());
      x= ob.readObject();
    } catch (Exception e) {
          e.printStackTrace();
    }   
   }
}

客户端:

public class Client  {
ObjectInputStream oin;
ObjectOutputStream oot;
private Socket socket = null;
public Client() {
    String serverAddress = "127.0.0.1";
    try {
     socket = new Socket(serverAddress, 9001);
        oin = new ObjectInputStream(socket.getInputStream());
        oot = new ObjectOutputStream(socket.getOutputStream());
        System.out.println("hello i am a client");
        oot.writeObject(x);
    } catch (Exception e) {
    e.printStackTrace();
    }
}
public static void main(String[] args) throws Exception {
    Client client = new Client();
}
}

Answer 1:

您必须声明ObjectOutputStream你声明之前ObjectInputStream

当你创建一个ObjectInputStream ,它等待从数据ObjectOutputStream 。 它等待的数据(头)。

public ObjectInputStream(InputStream in) throws IOException {
     verifySubclass();
     bin = new BlockDataInputStream(in);
     handles = new HandleTable(10);
     vlist = new ValidationList();
     enableOverride = false;
     readStreamHeader(); //this is whats causing it to block
     bin.setBlockDataMode(true);
}


protected void readStreamHeader() throws IOException, StreamCorruptedException {
     short s0 = bin.readShort();
     short s1 = bin.readShort();
     if (s0 != STREAM_MAGIC || s1 != STREAM_VERSION) {
          throw new StreamCorruptedException(String.format("invalid stream header: %04X%04X", s0, s1));
     }
}

如果声明ObjectOutputStream第一,它发送的数据,这是不堵



文章来源: Send object via socket