简体   繁体   English

使用Java套接字发送ByteArray(Android编程)

[英]Sending ByteArray using Java Sockets (Android programming)

I have this Java code that sends string with Socket. 我有使用Socket发送字符串的Java代码。 I can use the same code for Android. 我可以为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();
            }
        }
    }
}

Now, I need to send binary information encoded in ByteArray. 现在,我需要发送以ByteArray编码的二进制信息。 What might be the best ways to do this? 最好的方法是什么? I'm considering converting the ByteArray into string to use the same method, but I guess one can send the byte array information directly using Java Sockets. 我正在考虑将ByteArray转换为字符串以使用相同的方法,但是我猜想可以使用Java套接字直接发送字节数组信息。

只需在OutputStream上调用write(byte[] a) ,即从套接字获得的那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM