【问题标题】:Server/client communication服务器/客户端通信
【发布时间】: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)

一旦我将端口号更改为新端口号,它会运行一次,下次如果您想再次运行它,则需要更新端口号。我没有得到原因,因为我关闭了套接字,并且我认为该端口将在下一次运行时保持空闲。

【问题讨论】:

标签: java sockets io ports


【解决方案1】:

关于第二个问题:

不确定是什么原因造成的,但为了避免您的代码抛出未经检查的异常的可能性是原因,您应该在 finally 子句中关闭您的资源:

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

【讨论】:

  • 不,运营商最终什么都没有改变。
  • 您如何运行您的程序以及如何终止它?
  • 首先我运行服务器(上),然后我启动客户端(这里不介绍)。在每个文件的末尾我都有 System.exit(0);
  • 对我来说,您的程序似乎永远不会退出 while 循环,或者 s.close() 或 ss.close() 之一抛出异常,从而阻止套接字正确关闭。
猜你喜欢
  • 1970-01-01
  • 2012-12-26
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 2011-07-06
  • 2012-04-19
相关资源
最近更新 更多