尝试套接字写入时出现套接字关闭错误(bytearray)

时间:2017-12-06 20:59:50

标签: javascript java arrays sockets serversocket

以下代码触发以下错误:

错误:发送命令时出现异常:套接字已关闭

    public synchronized void sendCommand(final ServerCommand pServerCommand) {

    if (pServerCommand == null) {
        return;
    }

    try {
        //byte array to write server command
        ByteArrayOutputStream baosData = new ByteArrayOutputStream();
        DataOutputStream osData = new DataOutputStream(baosData);
        //byte array that will be used to write on socket
        //this will contain length of ByteArrayData and then ByteArrayData
        ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
        DataOutputStream osOut = new DataOutputStream(baosOut);

        //write command into osData byte array
        pServerCommand.write(osData);
        //write length of command into main byte array
        osOut.writeShort(baosData.size());
        //write command into main byte array
        baosData.writeTo(baosOut);

        OutputStream out = this.getSocket()
                               .getOutputStream();
        //write main byte array on socket
        byte[] data = baosOut.toByteArray();
        out.write(data, 0, data.length);
        out.flush();
    } catch (IOException e) {
        Log.pt("Exception when sending command", e.getMessage());
        // Socket is possibly closed
    }

}

1 个答案:

答案 0 :(得分:0)

无论出于何种原因,您正在编写的套接字都将关闭。它没有打开,它已经关闭了,或者它在另一端关闭,显然是服务器。

一些建议。首先,将所有数据准备代码移动到返回byte []的方法。套接字代码很难,不会将其与操纵数据的代码混合在一起。

其次,确保套接字实际打开。那不是给定的。