28

シリアル化されたオブジェクトをソケット チャネル経由で送信したいと考えています。「こんにちは友達」の文字列をシリアル化されたオブジェクトとして作成し、このオブジェクトをソケットチャネルに書き込み、反対側で同じオブジェクトを読み取ってデータを取得したい.

Java を使用してやりたいことすべてSocketChannel。これを行う方法?以下のように試しましたが、受信側でデータを取得できませんでした。

private static void writeObject(Object obj, SelectionKey selectionKey) {
    ObjectOutputStream oos;
    try {
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        oos = new ObjectOutputStream(Channels.newOutputStream(channel));

        oos.writeObject(obj);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

private static Object readObject(SelectionKey selectionKey) {
    ObjectInputStream ois;
    Object obj = new Object();
    SocketChannel channel = (SocketChannel) selectionKey.channel();
    try {
        ois = new ObjectInputStream(Channels.newInputStream(channel));
        obj = ois.readObject();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return obj;
}
4

1 に答える 1

37

SocketChannel の処理が不完全なようです。バイトを転送する SocketChannel のこの完全な例を参照してください。

/*
 * Writer
 */
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class Sender {
    public static void main(String[] args) throws IOException {
        System.out.println("Sender Start");

        ServerSocketChannel ssChannel = ServerSocketChannel.open();
        ssChannel.configureBlocking(true);
        int port = 12345;
        ssChannel.socket().bind(new InetSocketAddress(port));

        String obj ="testtext";
        while (true) {
            SocketChannel sChannel = ssChannel.accept();

            ObjectOutputStream  oos = new 
                      ObjectOutputStream(sChannel.socket().getOutputStream());
            oos.writeObject(obj);
            oos.close();

            System.out.println("Connection ended");
        }
    }
}

そしてリーダー

/*
 * Reader
 */
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class Receiver {
    public static void main(String[] args) 
    throws IOException, ClassNotFoundException {
        System.out.println("Receiver Start");

        SocketChannel sChannel = SocketChannel.open();
        sChannel.configureBlocking(true);
        if (sChannel.connect(new InetSocketAddress("localhost", 12345))) {

            ObjectInputStream ois = 
                     new ObjectInputStream(sChannel.socket().getInputStream());

            String s = (String)ois.readObject();
            System.out.println("String is: '" + s + "'");
        }

        System.out.println("End Receiver");
    }
}

最初にサーバーを起動し、次にレシーバーを起動すると、次の出力が得られます。

サーバーのコンソール

Sender Start
Connection ended

受信機のコンソール

Receiver Start
String is: 'testtext'
End Receiver

これは最善の解決策ではありませんが、Java の使用法に従います。ServerSocketChannel

于 2009-09-21T06:59:29.167 に答える