我有一个程序可以监听来自客户端的连接。
import java.io.*;
import java.net.*;
class SocketExampleServer {
public static void main(String [] args) throws Exception {
int port = 5665;
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting incoming connection...");
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
String x = null;
try {
while ((x = dis.readUTF()) != null)
{
System.out.println(x);
out.writeUTF(x.toUpperCase());
}
}
catch(IOException e)
{
System.err.println("Client closed its connection.");
}
catch(Exception e)
{
System.err.println("Unknown exception");
}
s.close();
ss.close();
dis.close();
out.close();
System.exit(0);
}
}
事情是这样的
System.out.println(x);
out.writeUTF(x.toUpperCase());
只执行第二行。如果一旦获得增益就交换该行,则仅执行第二行。这是什么原因呢? 当我第二次运行程序时,还有一件事会抛出此错误:
Exception in thread "main" java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at SocketExampleServer.main(SocketExampleServer.java:9)
一旦我将端口号更改为新端口号,它就会运行一次,下次如果您想再次运行它,则需要更新端口号。我没有得到原因,因为我关闭了套接字,并且在我看来,该端口将在下次运行时保持空闲状态。
最佳答案
关于第二个问题:
不确定是什么原因导致的,但为了避免代码抛出非检查异常的可能性,您应该在finally子句中关闭资源:
ServerSocket ss;
try {
...
}
finally {
if (ss.close() != null) {
ss.close();
}
}
关于java - 服务器/客户端通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9197748/