2014-11-09 235 views
1

我想通過套接字發送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(); 
} 
} 

回答

1

你聲明ObjectInputStream之前,您必須聲明ObjectOutputStream

當您創建一個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第一,它發送的數據,這是不會阻止

相關問題