Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用writeBytes的Java客户端套接字_Java_Sockets - Fatal编程技术网

使用writeBytes的Java客户端套接字

使用writeBytes的Java客户端套接字,java,sockets,Java,Sockets,我正在从缓冲区读取字符串并将其写入服务器。我遇到的问题是,当我保持套接字打开并在循环中写入时,服务器从未接收到字符串。 当我使用此选项时: try { Socket send = new Socket("localhost", 1490); DataOutputStream out = new DataOutputStream(send.getOutputStream()); String message = null;

我正在从缓冲区读取字符串并将其写入服务器。我遇到的问题是,当我保持套接字打开并在循环中写入时,服务器从未接收到字符串。 当我使用此选项时:

    try {       
        Socket send = new Socket("localhost", 1490);
        DataOutputStream out = new DataOutputStream(send.getOutputStream());
        String message = null;
        while ((message = buffer.get()) != null){
            out.writeBytes(message);
        }
        out.close();
        send.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
服务器不接收字符串,但当我这样做时,它会正常工作:

    try {       

        String message = null;
        while ((message = buffer.get()) != null){
            Socket send = new Socket("localhost", 1490);
            DataOutputStream out = new DataOutputStream(send.getOutputStream());
                    out.writeBytes(message);
            out.close();
            send.close();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

显然,我不想一直打开和关闭插座。有什么问题吗?

即使关闭套接字,数据也没有写入套接字?(在您的第一个片段中,即)

还有,你试过使用冲洗法吗?您可以在此处阅读:(),您的代码如下所示:

try {       
    Socket send = new Socket("localhost", 1490);
    DataOutputStream out = new DataOutputStream(send.getOutputStream());
    String message = null;
    while ((message = buffer.get()) != null){
        out.writeBytes(message);
        out.flush();
    }
    out.close();
    send.close();
} catch (IOException ex) {
    ex.printStackTrace();
}

每次要发送数据包时,都需要刷新套接字。 关闭套接字会强制自动刷新,这解释了为什么数据会在套接字关闭时发送

让我猜一猜

buffer.get()方法是否阻塞?如果是这样,那么问题在于
out.writeBytes(message)
不能保证将整个字节表示形式推送到服务器。相反您的客户机很可能有缓冲字节等待刷新到服务器

如果是这样,那么在每次调用
writeBytes
后调用flush将解决问题

但是如果
buffer.get()
方法没有阻塞,那么调用flush不会有任何区别。事实上,这只会增加网络流量。所以加上“以防万一”是个坏主意



另一种可能是服务器端代码有问题。

是的,我确实尝试了flush,但仍然存在相同的问题。缓冲区总是有字符串,所以我认为套接字实际上不会关闭。但是为什么我的留言还没有收到?谢谢。是的,buffer.get()确实会阻塞,但我确实在每次调用writeBytes后尝试刷新缓冲区,但仍然存在相同的问题。还有其他想法吗?