在具有端点的端口上侦听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();
我省略了一些部分,所以您可能会检测到错误,但此时代码工作正常
# 1 楼答案
您可以在本地主机端口60802上侦听。将接受该IP/端口上的所有连接。除此之外,服务器代码还需要:
(或者,您可以将服务器代码放在处理这些内容的反向代理后面,并重写请求URL。但这可能会破坏您使用套接字执行此操作的目的……)
但坦率地说,使用套接字编写HTTP服务器是个坏主意。大量的工作,您可能会得到一个无法正确实现HTTP规范的服务。您最好使用现有的web服务器/容器(例如Tomcat、Jetty、Glassfish、SpringBoot等)或Apache HttpComponents库
# 2 楼答案
服务器绑定到特定的TCP端口(以及接口,如果提供)。 如果您只想在/json路径上给出响应,只需做一个检查URL的条件语句
# 3 楼答案
如果您使用SpringBoot来装载服务器和web服务,那么将比重新编写所有代码容易得多
请看一看: Building a RESTful Web Service with Spring Boot Actuator
然后,您可以为每组web服务开发应用程序,并为每组web服务在
application.properties
文件下指定特定端口: