【发布时间】:2012-03-01 03:35:23
【问题描述】:
我有一个程序可以监听来自客户端的连接。
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)
一旦我将端口号更改为新端口号,它会运行一次,下次如果您想再次运行它,则需要更新端口号。我没有得到原因,因为我关闭了套接字,并且我认为该端口将在下一次运行时保持空闲。
【问题讨论】:
-
Have look at the actual ports,也许你可以看到哪个进程一直在绑定套接字。