我想通过套接字信道上发送一个序列化的对象。 我想使“您好朋友”字符串作为序列化对象,然后同时在另一端我想读相同的对象和检索数据写在插座通道此对象。

所有这些事情我想使用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;
}
有帮助吗?

解决方案

您的SocketChannel处理似乎是不完整的,看到这样的完成例如对于SocketChannels传输一个字节:

/*
 * 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的使用

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top