2009-09-21 13 views
24

quiero transmitir un objeto serializado por un canal de zócalo. quiero hacer "Hola amigo" cadena como objeto serializado y luego escribir este objeto en el canal de toma, mientras que en el otro extremo quiero leer el mismo objeto y recuperar los datos.¿Cómo enviar y recibir objeto serializado en el canal de toma

Todas estas cosas que quieren hacer uso de Java SocketChannel. ¿Como hacer esto? He intentado como a continuación, pero no obtuve ningún dato en el lado del destinatario.

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; 
} 
+0

La pregunta no se encuentra! – tuergeist

+0

¿Ya está abierto y conectado su SocketChannel? – tuergeist

+0

sí canal de zócalo está abierto y conectado –

Respuesta

31

Su manejo SocketChannel parece ser incompleta, vea este ejemplo completa para SocketChannels transferencia de un 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"); 
     } 
    } 
} 

y el lector

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

Al empezar el servidor , entonces el receptor, obtendrá el siguiente resultado:

la consola del servidor

Sender Start 
Connection ended 

consola del receptor

Receiver Start 
String is: 'testtext' 
End Receiver 

Esta no es la mejor solución, pero sigue su uso de Java ServerSocketChannel

+0

Gracias por su ayuda –

+2

Si te gusta la respuesta, te agradecería si lo acepta;) – tuergeist

+0

¿Qué quiere decir con "no es la mejor solución". ¿Podrías elaborar algo más? Además, si envuelve una secuencia alrededor de un canal, ¿pierde el rendimiento de NIO? ¡Gracias! – Jeach

Cuestiones relacionadas