如何在套接字通道中发送和接收序列化对象
问题描述:
我想通过套接字通道发送序列化对象。 我想让“Hi friend”字符串作为序列化对象,然后在socket通道中写入这个对象,而在另一端我想读取同一个对象并检索数据。如何在套接字通道中发送和接收序列化对象
我想用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
的问题是缺少! – tuergeist 2009-09-21 06:50:07
您的SocketChannel是否已经打开并连接? – tuergeist 2009-09-21 06:56:06
是套接字通道是开放和连接 – 2009-09-22 04:31:05