Sending ByteArray using Java Sockets (Android programming)

谁说我不能喝 提交于 2019-12-11 10:55:48

问题


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();
            }
        }
    }
}

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.


回答1:


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



来源:https://stackoverflow.com/questions/29178724/sending-bytearray-using-java-sockets-android-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!