소켓 채널에서 직렬화 된 객체를 보내고받는 방법
문제
소켓 채널을 통해 직렬화 된 객체를 전송하고 싶습니다. "Hi Friend"문자열을 직렬화 된 객체로 만들고 소켓 채널 에이 객체를 작성하고 다른 쪽 끝에서는 동일한 객체를 읽고 데이터를 검색하고 싶습니다.
내가 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;
}
해결책
양말 채널 취급은 불완전한 것 같습니다. 완벽한 바이트를 전송하는 SOODTCHANNELS의 예 :
/*
* 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
제휴하지 않습니다 StackOverflow