我的套接字程序有问题

时间:2011-05-09 14:52:38

标签: sockets osgi

我写了一个与套接字通信的程序。但我不知道他们为什么不工作。

服务器代码:

this.serverSocket = new ServerSocket(ServerConnector.port);
        this.socketListener = this.serverSocket.accept();
        System.out.println(this.socketListener.getPort());

        this.objIn = new ObjectInputStream(this.socketListener.getInputStream());
        System.out.println("1");

        this.objOut = new ObjectOutputStream(this.socketListener.getOutputStream());
        System.out.println("1");

        this.objOut.writeInt(19999);
        System.out.println("1");

        this.objOut.writeObject(new Date());
        System.out.println("1");

客户代码:

this.clientSocket = new Socket(ClientConnector.host, ClientConnector.port);

        System.out.println(this.clientSocket.getPort());
        this.objIn = new ObjectInputStream(this.clientSocket.getInputStream());
        System.out.println("1");
        this.objOut = new ObjectOutputStream(this.clientSocket.getOutputStream());
        System.out.println("1");

        int i = (Integer) this.objIn.readInt();
        System.out.println(i);
        Date date = (Date) this.objIn.readObject();

事实是,他们没有显示我建议通过的任何信息(19999和日期),他们甚至无法打印一行“1”(我添加了测试)。这意味着即使下面的行也无法正常工作。我真的很困惑,谁能搞清楚错误?

this.objIn = new ObjectInputStream(this.clientSocket.getInputStream());

1 个答案:

答案 0 :(得分:-1)

您很可能会遇到Nagle's Algorithm的影响。试图优化TCP中的数据包发送。如果要立即发送数据,则需要使用套接字接口上的setTcpNoDelay方法禁用它。

P.S。不知道为什么这个问题被标记为 osgi ,因为它与OSGi完全无关。