H
Henry
I had a NIO problem.
I tried to open a socket channel, and grep a HTML page from HTTP GET.
I did it success if I open and close socket channel everytime I send a
request and get the response.
However, if I keep open the socket channel and send multiple requests,
I'll get IOException.
Does anybody know how to solve this problem? Thanks in advance!
Note: I don't want to fire requests in parallel but one by one
sample code:
=============================================================
private Charset charset = Charset.forName("ISO-8859-1");
private SocketChannel channel;
try
{
// do connection
InetSocketAddress socketAddress =
new InetSocketAddress( "www.mydomain.com", 80);
channel = SocketChannel.open(socketAddress);
// send request #1
channel.write(charset.encode("GET /page1.html HTTP/1.0\r\n\r\n") );
// read response #1
ByteBuffer buffer = ByteBuffer.allocate(1024);
while ((channel.read(buffer)) != -1)
{
buffer.flip();
System.out.println(charset.decode(buffer));
buffer.clear();
}
// send request #2
channel.write(charset.encode("GET /page2.html HTTP/1.0\r\n\r\n") );
// read response #2
// program threw "java.io.IOException: Read failed" error
while ((channel.read(buffer)) != -1)
{
buffer.flip();
System.out.println(charset.decode(buffer));
buffer.clear();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (channel != null)
{
try
{
channel.close();
} catch (IOException e) {}
}
}
=============================================================
I tried to open a socket channel, and grep a HTML page from HTTP GET.
I did it success if I open and close socket channel everytime I send a
request and get the response.
However, if I keep open the socket channel and send multiple requests,
I'll get IOException.
Does anybody know how to solve this problem? Thanks in advance!
Note: I don't want to fire requests in parallel but one by one
sample code:
=============================================================
private Charset charset = Charset.forName("ISO-8859-1");
private SocketChannel channel;
try
{
// do connection
InetSocketAddress socketAddress =
new InetSocketAddress( "www.mydomain.com", 80);
channel = SocketChannel.open(socketAddress);
// send request #1
channel.write(charset.encode("GET /page1.html HTTP/1.0\r\n\r\n") );
// read response #1
ByteBuffer buffer = ByteBuffer.allocate(1024);
while ((channel.read(buffer)) != -1)
{
buffer.flip();
System.out.println(charset.decode(buffer));
buffer.clear();
}
// send request #2
channel.write(charset.encode("GET /page2.html HTTP/1.0\r\n\r\n") );
// read response #2
// program threw "java.io.IOException: Read failed" error
while ((channel.read(buffer)) != -1)
{
buffer.flip();
System.out.println(charset.decode(buffer));
buffer.clear();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (channel != null)
{
try
{
channel.close();
} catch (IOException e) {}
}
}
=============================================================