【发布时间】:2019-01-03 08:45:27
【问题描述】:
我已经使用 Java 中的套接字创建了一个服务器,它已准备好接收 HTTP 请求并发出 HTTP 响应。
服务器位于我 PC 的端口上,但我只想监听“端点”,我的意思是,我想安装服务器,即在 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();
我省略了一些部分,所以你可能检测到错误,但此时代码运行良好。
【问题讨论】: