服务器/客户端通信

时间:2012-02-08 16:48:46

标签: java sockets io ports

我有一个程序可以监听来自客户端的连接。

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)

将端口号更改为新端口后,它会运行一次,如果您想再次运行端口号,则需要更新端口号。我没理由这个原因我关闭套接字,在我看来,端口应该保持空闲,以便下次运行。

1 个答案:

答案 0 :(得分:2)

关于第二个问题:

不确定导致这种情况的原因,但为了避免代码抛出未检查异常的可能性,原因是,您应该在finally子句中关闭资源:

ServerSocket ss;
try {
...
} 
finally {
    if (ss.close() != null) {
                ss.close();
    }    
}