I’m trying to build a simple web server in Java as practice but I’m running into a very strange issue. When I attempt to read the InputStream from the Socket, sometimes there is no data to be read.
The process I’m following is this:
I create a ServerSocket, listening on port 80, and call accept() to get a Socket. I then send a request from my browser (Firefox) to localhost, which triggers the accept() to return the Socket.
Sometimes, it will read the HTTP request perfectly. Other times, it fails to read any data (read() returns a -1).
Here is some sample code to illustrate what I’m doing, without any exception handling thrown in:
ServerSocket serv = new ServerSocket(80);
while (true)
{
Socket con = ServerSocket.accept();
InputStream input = con.getInputStream();
bytes[] bytes = new bytes[4000000]; // for simplicity, I figured I'd
// just make the array huge for now
int bytesRead = input.read(bytes);
if (bytesRead > 0)
{
StringBuffer sBuffer = new StringBuffer(bytesRead);
for (int i = 0; i < bytesRead; i++)
{
sBuffer.append((char) bytes[i]);
}
System.out.println(sBuffer.toString());
}
}
EDIT: I’ve also tried using a BufferedInputStream and BufferedReader to not avail.
One socket can receive more packets. So you should create a new thread for every socket. Something like:
Then you need to create the Client class which implements the runable interface.