本文介绍了发送的ByteArray使用Java套接字(Android的编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的Java code发送字符串插座。我可以使用相同的code为Android。

I have this Java code that sends string with Socket. I can use the same code for 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 codeD。
什么可能是做到这一点的最好方法是什么?我正在考虑转换成的ByteArray字符串,用同样的方法,但我想我们可以直接使用Java套接字发送的字节数组的信息。

Now, I need to send binary information encoded in 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.

推荐答案

只是叫写(字节[]一)的OutputStream 您从插座中获得的。

just call write(byte[] a) on the OutputStream the one you get from the socket.

这篇关于发送的ByteArray使用Java套接字(Android的编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:37