有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在具有端点的端口上侦听java服务器

我使用Java中的socket创建了一个服务器,它可以接收HTTP请求并发出HTTP响应。 服务器在我电脑的一个端口上,但我只想监听一个“端点”,我的意思是,我想把服务器安装在localhost:60802/json上。 这可能吗?我的代码在这里:

            PORT = Integer.parseInt(portSelection.getText());
            th =  new Thread(new Runnable() {

                //String file;
                @Override
                public void run() {
                    try{
                        server = new ServerSocket(PORT);

                        while(open) {
                            //Accept connections
                            connection = server.accept();

                            in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

                            try {
                                String line="";

                                while ((line=in.readLine())!= null && !line.equals("")){log.append(line);}                                                              
                                in.close();
                            }catch (Exception e1) {
                            }
                        }
                    }catch (EOFException e1 ) {
                        e1.printStackTrace();
                    }catch (BindException e1) {
                        log.setText("Error. Port "+PORT+" already in use.");
                        open=false;
                    }catch (SocketException e1) {

                    }catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });
            th.start();

我省略了一些部分,所以您可能会检测到错误,但此时代码工作正常


共 (3) 个答案

  1. # 1 楼答案

    I want to mount the server i.e. on localhost:60802/json. Is this possible?

    您可以在本地主机端口60802上侦听。将接受该IP/端口上的所有连接。除此之外,服务器代码还需要:

    1. 读取HTTP请求
    2. 解码第一行以提取请求URL
    3. 确定URL的路径是否与“端点”URL的路径匹配;i、 e.“/json/*”
      • 如果是,则继续
      • 如果没有,则发送适当的HTTP错误响应;e、 g.404未找到

    (或者,您可以将服务器代码放在处理这些内容的反向代理后面,并重写请求URL。但这可能会破坏您使用套接字执行此操作的目的……)


    但坦率地说,使用套接字编写HTTP服务器是个坏主意。大量的工作,您可能会得到一个无法正确实现HTTP规范的服务。您最好使用现有的web服务器/容器(例如Tomcat、Jetty、Glassfish、SpringBoot等)或Apache HttpComponents库

  2. # 2 楼答案

    服务器绑定到特定的TCP端口(以及接口,如果提供)。 如果您只想在/json路径上给出响应,只需做一个检查URL的条件语句

  3. # 3 楼答案

    如果您使用SpringBoot来装载服务器和web服务,那么将比重新编写所有代码容易得多

    请看一看: Building a RESTful Web Service with Spring Boot Actuator

    然后,您可以为每组web服务开发应用程序,并为每组web服务在application.properties文件下指定特定端口:

    server.port= 60802