将函数暴露给其他进程

发布于 2024-07-15 20:28:20 字数 649 浏览 5 评论 0原文

我正在使用这段代码,它使用套接字公开一个简单的函数:

while (true) {
  try {
    ServerSocket serverSocket = new ServerSocket(7070);
    Socket clientSocket = serverSocket.accept();
    String input = (new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))).readLine();
    synchronized (this.map) {
      ObjectOutputStream o = new ObjectOutputStream(clientSocket.getOutputStream());
      o.writeChars(map.get(input));
      o.close();
    }
    clientSocket.close();
    serverSocket.close();
  } catch(Exception e) {
    e.printStackTrace();
  }
}



我究竟做错了什么? 日志显示它卡在输入接收行中,有时会抛出异常,表示套接字正在使用中

I'm using this piece of code that exposes a simple function using a socket:

while (true) {
  try {
    ServerSocket serverSocket = new ServerSocket(7070);
    Socket clientSocket = serverSocket.accept();
    String input = (new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))).readLine();
    synchronized (this.map) {
      ObjectOutputStream o = new ObjectOutputStream(clientSocket.getOutputStream());
      o.writeChars(map.get(input));
      o.close();
    }
    clientSocket.close();
    serverSocket.close();
  } catch(Exception e) {
    e.printStackTrace();
  }
}

What am I doing wrong? logging shows that it gets stuck in the input reception line and it sometimes throws an exception saying that the socket is in use

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谜兔 2024-07-22 20:28:20

对于初学者来说,您在循环内创建 ServerSocket,这显然不是您想要的。 您只想创建一次,然后有一个不断从套接字读取数据的循环。

For starters, you're create the ServerSocket [i]inside[/i] the loop, which is obviously not what you want. You only want to create it once, then have a loop that constantly reads from the sockets.

关于从前 2024-07-22 20:28:20

readLine() 被卡住,因为您忘记刷新发送者(另一个进程)的输出流。

使用套接字时,计算机将缓冲一些数据(通常为 4KB),因为通过网络发送少量数据的成本很高。 因此,如果您的数据较少,您需要告诉它“立即发送”。

The readLine() gets stuck because you forgot to flush the output stream of the sender (the other process).

When working with sockets, the computer will buffer some data (usually 4KB) because sending small amounts of data over the network is expensive. Therefore, if you have less data, you need to tell it "send now".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文