LoginSignup
6
6

More than 5 years have passed since last update.

bash で TCP 通信して Java オブジェクトを送信する

Last updated at Posted at 2015-11-14

『bash で TCP 通信』 の記事を読んで、シリアライズした Java のオブジェクトを送れるなあ、なんて思ってサンプルを書いてみた。

Main.java
import java.io.*;
import java.net.*;

public class Main {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        try (ServerSocket server = new ServerSocket(38080);
                Socket socket = server.accept();
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
            String obj = (String) in.readObject();
            System.out.println(obj); // "Hello, Java!!"
        }
    }
}
HelloJava.sh
#!/bin/bash
exec 3> /dev/tcp/127.0.0.1/38080
echo -en "\xAC\xED\x00\x05\x74\x00\x0D\x48\x65\x6C\x6C\x6F\x2C\x20\x4A\x61\x76\x61\x21\x21" >&3
# "Hello, Java!!" をシリアライズして16進数表現にしたもの。この文字列は SerializeSample.java で出力した。
SerializeSample.java
import java.io.*;
public class SerializeSample {
    public static void main(String... args) throws Exception {
        try (ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo)) {
            oo.writeObject("Hello, Java!!");
            oo.flush();
            byte[] bytes = bo.toByteArray();
            for (byte b : bytes) {
                System.out.printf("\\x%02X", b);
            }
        }
    }
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6