Java多线程Web服务器-无法接收多个GET请求 [英] Java Multithreaded Web Server - Not recieving multiple GET requests
问题描述
我有一个非常基础的多用途Web服务器的启动,只要一次收到一个GET请求,它就可以接收所有GET请求.
I have the starts of a very basic multi-hreaded web server, it can recieve all GET requests as long as they come one at a time.
但是,当同时收到多个GET请求时,有时会全部收到,而有时却丢失了一些.
However, when multiple GET requests come in at the same time, sometimes they all are recieved, and other times, some are missing.
我通过创建一个带有多个指向我的网络服务器的图像标签的html页面并在firefox中打开该页面来进行了测试.我总是使用shift + refresh.
I tested this by creating a html page with multiple image tags pointing to my webserver and opening the page in firefox. I always use shift+refresh.
这是我的代码,我必须做的是根本上错误的事情.
Here is my code, I must be doing something fundamentally wrong.
public final class WebServer
{
public static void main(String argv[]) throws Exception
{
int port = 6789;
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(port);
}
catch(IOException e)
{
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
while(true)
{
try
{
Socket clientSocket = serverSocket.accept();
new Thread(new ServerThread(clientSocket)).start();
}
catch(IOException e)
{
}
}
}
}
public class ServerThread implements Runnable
{
static Socket clientSocket = null;
public ServerThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
public void run()
{
String headerline = null;
DataOutputStream out = null;
BufferedReader in = null;
int i;
try
{
out = new DataOutputStream(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while((headerline = in.readLine()).length() != 0)
{
System.out.println(headerline);
}
}
catch(Exception e)
{
}
}
推荐答案
我实际上发现了问题所在:
I actually discovered the problem was this:
static Socket clientSocket = null;
一旦我移除了静电,它现在就可以正常工作了.
Once I removed the static, it works perfectly now.
这篇关于Java多线程Web服务器-无法接收多个GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!