Problem getting input and output stream from socket in java
I debugged the program and observed that it is stopped when it wants to get input stream from socket:
public Chat(Socket s) throws IOException {
input = new ObjectInputStream(s.getInputStream()); // stopped here
output = new ObjectOutputStream(s.getOutputStream());
initComponents();
}
I have closed the open streams and the socket before calling above constructor here:
Socket socket = listeningSocket.accept();
disconnect();
Chat c = new Chat(socket);
and here is the disconnect method:
private void disconnect() throws IOException {
input.close();
output.close();
client.close();
}
input, output and client are initiated here:
client = new Socket(chatServer, chatPort);
input = new ObjectInputStream(client.getInputStream());
output = new ObjectOutputStream(client.getOutputStream());
this is the stack trace when the program is suspended:
Thread [main] (Suspended)
SocketInputStream.socketRead0(FileDescriptor, byte[], int, int, int) line: not available [native method]
SocketInputStream.read(byte[], int, int) line: 146
ObjectInputStream$PeekInputStream.read(byte[], int, int) line: 2282
ObjectInputStream$PeekInputStream.readFully(byte[], int, int) line: 2295
ObjectInputStream$BlockDataInputStream.readShort() line: 2766
ObjectInputStream.readStreamHeader() line: 797
ObjectInputStream.<init>(InputStream) line: 297
Chat.<init>(Socket) line: 20开发者_高级运维
Client$5.run() line: 310
Client.clientListen() line: 320
Client.access$7(Client) line: 302
Client$6.run() line: 350
Client.main(String[]) line: 352
please help thanks :)
From ObjectInputStream's constructor's documentation:
This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.
Is anything being written to the socket from the other end? Are you flushing the stream from the other end?
The ObjectOutputStream's constructor has documentation saying that users may wish to flush to the stream so that inputstreams don't block.
Is it stopping on that line specifically or possibly inside the constructor, or even inside the s.getInputStream() call? Both the constructor and getInputStream() can throw IOException.
Not to belabor the point, but did you jump into the constructor call and the getInputStream() method when you debugged it?
Like Atreys said above it would probably be useful to see the stack trace.
精彩评论