将函数暴露给其他进程
我正在使用这段代码,它使用套接字公开一个简单的函数:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于初学者来说,您在循环内创建 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.
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".