使用 Java 套接字发送 ByteArray(Android 编程)
Sending ByteArray using Java Sockets (Android programming)
我有这个 Java 代码可以用 Socket 发送字符串。我可以对 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 套接字直接发送字节数组信息。
只需在 OutputStream
上从套接字中调用 write(byte[] a)
。
我有这个 Java 代码可以用 Socket 发送字符串。我可以对 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 套接字直接发送字节数组信息。
只需在 OutputStream
上从套接字中调用 write(byte[] a)
。