[ Android ] TCP・UDP通信

TCP、UDP送受信を簡単に。

・UDP送信

int port = 12345;
InetAddress inetAddress = InetAddress.getByName("192.168.1.1");
byte[] buff = "Hellow".getBytes();
try (DatagramSocket socket = new DatagramSocket(port)) {
    DatagramPacket packet = new DatagramPacket(
        buff,
        buff.length,
        inetAddress,
        port
    );
    socket.send(packet);
} catch (Exception e) {
    e.printStackTrace();
}

・UDP受信

int port = 12345;
try (DatagramSocket socket = new DatagramSocket(port)) {
    byte[] buff = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buff, buff.length);
    socket.receive(packet);
    return packet;
} catch (Exception e) {
    e.printStackTrace();
}

タイムアウト追加
socket.setSoTimeout(15000);

・TCP送受信

int port = 12345;
String ipAddress = "192.168.1.1";
try (Socket socket = new Socket(ipAddress, port);
     OutputStream out = socket.getOutputStream();
     InputStream in = socket.getInputStream()) {

    out.write(buff);
    out.flush();

    // wait
    Thread.sleep(100);

    byte[] tmpBuff = new byte[1024];
    int readSize = 0, offset = 0;
    while (-1 != (readSize = in.read(tmpBuff, offset, tmpBuff.length - offset))) {
        offset += readSize;
        if (offset >= tmpBuff.length) {
            break;
        }
    }

    byte[] recvBuff = new byte[offset];
} catch (Exception e) {
    e.printStackTrace();
}

タイムアウト
socket.setSoTimeout(15000);

ウエイト(送信後のWaitは無くても)
Thread.sleep(100);