作为实践,我正在尝试用Java构建一个简单的web服务器,但我遇到了一个非常奇怪的问题。当我尝试从InputStream读取Socket时,有时没有需要读取的数据。我所遵循的过程是:
我创建一个ServerSocket,监听端口80,并调用accept()获得一个Socket。然后,我从浏览器(火狐)向localhost发送请求,这将触发accept()返回Socket。
有时,它会完美地读取HTTP请求。其他情况下,它无法读取任何数据(read()返回a-1)。
下面是一些示例代码来说明我正在做的事情,没有任何异常处理:
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());
}
}编辑:我也尝试过使用BufferedInputStream和BufferedReader来不起作用。
发布于 2012-09-24 19:18:27
一个套接字可以接收更多的数据包。因此,您应该为每个套接字创建一个新线程。类似于:
while(true){
Socket socket = serv.accept();
Client client = new Client(socket);
new Thread(client).start();
}然后,您需要创建实现可运行接口的客户端类。
Socket socket;
public Client(Socket socket){
this.socket = socket;
}
public void run(){
while(socket.isConnected()){
//here reads the packets from the inputstream
}
}发布于 2012-09-24 19:21:40
从InputStream读取数据时,应该始终循环。不能保证所有数据都将从单个read()调用返回(循环直到接收到-1)。
https://stackoverflow.com/questions/12571233
复制相似问题