如何通过android套接字发送字符串或文件?

时间:2014-08-22 00:24:42

标签: java android string sockets

我刚刚在写入读取套接字时意识到 DataInputStream DataOutputStream 可以用来区分即将发生的输入。

检查此代码:

服务器端。 (接收字符串或文件)

Socket bSock = serverSocket.accept();
DataInputStream inp = new DataInputStream(bSock.getInputStream());

int iCode = inp.readInt();

        switch (iCode) {
                case Request.STATE_FILESHARING:
                    byte bp[] = new byte[iCode];

                    FileOutputStream fos = new FileOutputStream("s.pdf");
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    int bytesRead = inp.read(bp, 0, bp.length);
                    bos.write(bp, 0, bytesRead);
                    bos.close();
                    break;
                case Request.STATE_CONVERSATION:

                    requestFound = new Request(inp.readUTF());
                    sendToUI(requestFound);
                    break;
        }

客户端。 (发送字符串或文件)

Socket socket = new Socket(myServerAddress, SocketServerPORT);

DataOutputStream out = new DataOutputStream(socket.getOutputStream());

if (isThisFileMode()) {

            File myFile = new File(sLocationFile);
            byte[] mybytearray = new byte[(int) myFile.length()];
            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            bis.read(mybytearray, 0, mybytearray.length);

            out.writeInt(Request.STATE_FILESHARING);
            out.write(mybytearray, 0, mybytearray.length);
            out.flush();

} else {

            out.writeInt(Request.STATE_CONVERSATION);
            out.write(obReq.toString().getBytes());
            out.flush();

}

但我最终得到了错误。系统崩溃了! 我忘了添加什么?

1 个答案:

答案 0 :(得分:0)

  1. 您正在使用readUTF()但不是writeUTF().几乎所有DataInputStream和DataOutputStream的方法都是对称的:如果您致电readXXX(),则必须致电writeXXX()另一端。

  2. 你犯了通常的错误,认为read()填充了缓冲区。它只签约传输至少一个字节。你必须循环:

    while ((count = in.read(buffer)) > 0)
    {
        out.write(buffer, 0, count);
    }
    
  3. 您需要在服务器和客户端关闭套接字。