java服务器处理多个tcp连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3695082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:34:08  来源:igfitidea点击:

java server to handle multiple tcp connections

javamultithreadingsocketsnetworking

提问by Rob Turner

im trying to write a simple web server in java.

我正在尝试用 Java 编写一个简单的 Web 服务器。

right now ive only got a simple program but id like to extend it so that it can serve multiple browsers by establishing multiple tcp connections.

现在我只有一个简单的程序,但我喜欢扩展它,以便它可以通过建立多个 tcp 连接来为多个浏览器提供服务。

ive been reading about threading. my understanding is that you can make a new thread and that will continue as if its another program entirely. so with a new thread, it can be like there are 2 web servers which can serve 2 browsers, or x web servers which can serve x web browsers.

我一直在阅读有关线程的信息。我的理解是,您可以创建一个新线程,并且该线程将继续进行,就好像它完全是另一个程序一样。所以有了一个新线程,就好像有 2 个 Web 服务器可以为 2 个浏览器提供服务,或者 x 个 Web 服务器可以为 x 个 Web 浏览器提供服务。

im a bit lost on how to create new threads in java though and to give each new thread a connection.

我对如何在 Java 中创建新线程并为每个新线程提供连接有点迷茫。

my thoughts are that i would have a loop like this which gets new connections and passes each new connection to a new thread

我的想法是我会有一个这样的循环,它获取新连接并将每个新连接传递给一个新线程

// make new ServerSocket
while (true) {
     Socket newConn = serverSocket.accept();
     // make new thread, and pass in newConn
}

can someone give me some guidance on how to move forward? (also if ive made an error somewhere, please do point it out. im new to threaded programming so its entirely possible ive not properly understood it)

有人可以给我一些关于如何前进的指导吗?(如果我在某处犯了错误,请指出。我是线程编程的新手,所以完全有可能我没有正确理解它)

rob

edit:

编辑:

k thanks all.

k 谢谢大家。

i went and wrote something, that java tutorial helped a lot.

我去写了一些东西,那个java教程帮助了很多。

ive got a new issue now

我现在有一个新问题

i added a loop in my run() method in the new thread which contains a 10 second countdown (using Thread.sleep(1000)) whenever the server receives a request for an image, so i can see which threads are running when. (index.html has 4 images in it)

我在新线程的 run() 方法中添加了一个循环,该循环包含一个 10 秒倒计时(使用 Thread.sleep(1000))每当服务器收到图像请求时,这样我就可以看到哪些线程正在运行。(index.html 中有 4 张图片)

so i requested the index.html page and my server works fine. then i opened up about a dozen new tabs. my expectation was that the request for the index.html page would be instant but it would take 10 seconds for the images to be sent to the browser (because of that delay i put in there), at which point the server would receive the request for the next index.html page, and so on. overall, i thought that the dozen index.html pages would be served instantly while it would take 10 seconds for the 4 * 12 = 36 images to be served on all tabs.

所以我请求了 index.html 页面,我的服务器工作正常。然后我打开了大约十几个新标签。我的期望是对 index.html 页面的请求将是即时的,但将图像发送到浏览器需要 10 秒(因为我在那里设置了延迟),此时服务器将收到请求对于下一个 index.html 页面,依此类推。总的来说,我认为 12 个 index.html 页面会立即提供,而在所有选项卡上提供 4 * 12 = 36 个图像需要 10 秒。

what actually happened was it took 10 seconds to get the first 4 images, then 10 seconds for the next 4 images, etc. so rather than serving multiple web pages, my server just queues up requests and deals with one page at a time.

实际发生的情况是,获取前 4 个图像需要 10 秒,然后获取接下来的 4 个图像需要 10 秒,等等。因此,我的服务器只是将请求排队并一次处理一个页面,而不是提供多个网页。

i think my program is at fault. but i feel like i might not properly understand how a browser interacts with a server. i thought the browser requests new objects as the html page is parsed. so my server should be receiving dozens of requests if i open a dozen pages. i tried opening up several tabs in FF and then several windows in FF but this did not help.

我认为我的程序有问题。但我觉得我可能无法正确理解浏览器如何与服务器交互。我认为浏览器在解析 html 页面时会请求新对象。所以如果我打开十几页,我的服务器应该会收到几十个请求。我尝试在 FF 中打开几个选项卡,然后在 FF 中打开几个窗口,但这没有帮助。

HOWEVER, when i opened up IE, FF and Chrome, and i asked for index.html at different times (about 2 seconds apart), it looked like each browser was receiving the page simultaneously, in other words, at one point, there were 12 different images being served, 4 to each browser

但是,当我打开 IE、FF 和 Chrome,并在不同时间(相隔约 2 秒)请求 index.html 时,看起来每个浏览器都在同时接收页面,换句话说,在某一时刻,有提供 12 个不同的图像,每个浏览器 4 个

so i guess im looking for a bit of confirmation that this is the expected behavior? and if so, why is it that i could only see this behavior when i opened up 3 different browsers and not when i opened up multiple tabs?

所以我想我想确认一下这是预期的行为?如果是这样,为什么我只能在打开 3 个不同的浏览器时看到这种行为,而在打开多个标签时却看不到?

(for those that asked, i plan ok taking a networks course next year, but im trying to do some of the basic stuff now. so half self learning, half h/w)

(对于那些问的人,我计划明年参加网络课程,但我现在正在尝试做一些基本的东西。所以一半自学,一半 h/w)

回答by duffymo

You might also consider Nettyand Java NIO. There's more than one way to do it.

您也可以考虑Netty和 Java NIO。有不止一种方法可以做到。

回答by Asaph

Sun's classic Java tutorialincludes a section on programming with socketsthat walks you through an examplevery similar to the program you're trying to write.

Sun 的经典 Java 教程包括一个关于使用套接字编程的部分,该部分将引导您完成一个与您尝试编写的程序非常相似的示例

回答by Romain Hippeau

If you are looking for something robust look online for a working solution.
If it is for learning purposes, then create your own.
There are several ways to do this. The easiest is to do this As taken from the Java Tutorial:

如果您正在寻找可靠的东西,请在线查找可行的解决方案。
如果是为了学习目的,那就创建你自己的。
有几种方法可以做到这一点。最简单的方法是从Java 教程中获取

import java.net.*;
import java.io.*;
public class MultiServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        boolean listening = true;

        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        }

        while (listening)
        new MultiServerThread(serverSocket.accept()).start();

        serverSocket.close();
    }
}




import java.net.*;
import java.io.*;

public class MultiServerThread extends Thread {
    private Socket socket = null;
public MultiServerThread(Socket socket) {
super("MultiServerThread");
this.socket = socket;
}

public void run() {

try {
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(
                new InputStreamReader(
                socket.getInputStream()));

    String inputLine, outputLine;
    KnockKnockProtocol kkp = new KnockKnockProtocol();
    outputLine = kkp.processInput(null);
    out.println(outputLine);

    while ((inputLine = in.readLine()) != null) {
    outputLine = kkp.processInput(inputLine);
    out.println(outputLine);
    if (outputLine.equals("Bye"))
        break;
    }
    out.close();
    in.close();
    socket.close();

} catch (IOException e) {
    e.printStackTrace();
}
}

}

}

You would implement your logic for processing your requests in:

您将实现处理请求的逻辑:

KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);

You could optimize your code by putting your Threads in a Thread Pool so you did not need to create a new Thread each time.

您可以通过将线程放入线程池来优化代码,这样您就无需每次都创建一个新线程。

The part below is subjective and depends on the types of requests and what you do with each one. If you have a lot of concurrent client requests then NIO is the way to go.
If your requests are short and you have over 10 concurrent ones create a pool.
If your requests are more than 100, then I would start looking at NIO.

下面的部分是主观的,取决于请求的类型以及您对每个请求的处理方式。如果您有很多并发客户端请求,那么 NIO 是您的最佳选择。
如果您的请求很短并且您有超过 10 个并发请求,请创建一个池。
如果你的请求超过 100 个,那么我会开始关注 NIO。

回答by scphantm

a web server is nothing but a glorified socket server with messaging. tech has been around since the very first network connection was made. i had a project about a year and a half ago that was similar to what your trying to do. Java NIO is the best bet to start with, has connection and thread pooling and all the advanced stuff that a web server needs, but its a bit complicated. if you want a VERY good baseline to start with, check out http://www.quickserver.org/the system i wrote was based on this and it now handles about 45,000 devices on one server last i heard.

一个网络服务器只不过是一个带有消息传递的美化套接字服务器。自从第一个网络连接建立以来,技术就一直存在。大约一年半前,我有一个与您尝试做的类似的项目。Java NIO 是最好的选择,它具有连接和线程池以及 Web 服务器所需的所有高级功能,但它有点复杂。如果您想要一个非常好的基线,请查看http://www.quickserver.org/我编写的系统基于此,它现在在我上次听说的一台服务器上处理大约 45,000 台设备。