【问题标题】:Sending ByteArray using Java Sockets (Android programming)使用 Java Sockets 发送 ByteArray(Android 编程)
【发布时间】:2015-03-21 12:06:06
【问题描述】:

我有这个用 Socket 发送字符串的 Java 代码。我可以为 Android 使用相同的代码。

public class GpcSocket {

    private Socket socket;

    private static final int SERVERPORT = 9999;
    private static final String SERVER_IP = "10.0.1.4";

    public void run() {
        new Thread(new ClientThread()).start();
    }

    public int send(String str) {
        try {
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
            out.flush();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str.length();
    }

    class ClientThread implements Runnable {
        @Override
        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

现在,我需要发送以 ByteArray 编码的二进制信息。 最好的方法是什么?我正在考虑将 ByteArray 转换为字符串以使用相同的方法,但我想可以使用 Java 套接字直接发送字节数组信息。

【问题讨论】:

    标签: java android sockets bytearray


    【解决方案1】:

    只需在您从套接字获得的OutputStream 上调用write(byte[] a)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2021-09-07
      • 1970-01-01
      • 2011-08-06
      相关资源
      最近更新 更多