I using DataOutputStream
for send/receive byte stream to a server. First I discuss my important code parts then ask my question.
I have a send method as following:
protected static void sendMessage (Socket socket, byte[] b) throws IOException
{
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), 2048);
DataOutputStream serverOut = new DataOutputStream(bos);
serverOut.write(b, 0, b.length);
serverOut.flush();
}
I using above method for send message to server by DataOutputStream
instance.
Note: Socket
instance initialized before and send to this method as argument;
In additional I have a receive
method as following:
protected static void receive (Socket socket, byte[] b) throws IOException
{
BufferedInputStream bis = new BufferedInputStream (socket.getInputStream ());
DataInputStream serverIn = new DataInputStream (bis);
serverIn.readFully(b, 0, b.length);
}
In last step I show main
method :
public static void main(String[] args)
{
ServerSocketFactory socket_factory = ServerSocketFactory.getDefault();
InetAddress host = InetAddress.getByName("192.168.20.33");
ServerSocket server_socket = socket_factory.createServerSocket(1111,3,host);
Socket socket = server_socket.accept();
System.out.println(socket.isConnected());
byte[] request = new byte[]{48,48,48};
send(socket, request);
byte[] response = new byte[10];
receive(socket,response);
}
In normal situation all thing do fine but my question is:
When server down after test connection by socket.isConnected()
statement send
method work fine and any exception don't throw but when invoking receive
method , it throws a exception for unconnected host.
I confounded, what send
method doesn't throw exception when server is fail but receive
method throws exception when connection is lost?
Also is there way for checking connection in write
method similar readFully
method, for sample it throws a exception?
(Sorry if I am using the wrong terminology or grammar, I am learning english language.)