How to send and receive serialized object in socket channel

后端 未结 1 1258
无人及你
无人及你 2020-12-01 05:22

I want to transmit a serialized object over a socket channel. I want make \"Hi friend\" string as serialized object and then write this object in socket channel while in the

相关标签:
1条回答
  • 2020-12-01 05:49

    Your SocketChannel handling seems to be incomplete, see this complete example for SocketChannels transferring a byte:

    /*
     * 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");
            }
        }
    }
    

    And the Reader

    /*
     * 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");
        }
    }
    

    When you first start the Server, then the Receiver, you'll get the following output:

    Server's console

    Sender Start
    Connection ended
    

    Receiver's console

    Receiver Start
    String is: 'testtext'
    End Receiver
    

    This is not the best solution, but follows your use of Java's ServerSocketChannel

    0 讨论(0)
提交回复
热议问题