Thursday, April 28, 2011

how to write data to socket channel

is there any small working program for recieving from and sending data to client using java nio.

Actually i am unable to write to socket channel but i am able to read the incoming data how to write data to socket channel

Thanks Deepak

From stackoverflow
  • You can write data to a socket channel like so:

    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.charset.*;
    
    public class SocketWrite {
    
      public static void main(String[] args) throws Exception{
    
        // create encoder
        CharsetEncoder enc = Charset.forName("US-ASCII").newEncoder();  
    
        // create socket channel
        ServerSocketChannel srv = ServerSocketChannel.open();
    
        // bind channel to port 9001   
        srv.socket().bind(new java.net.InetSocketAddress(9001));
    
        // make connection
        SocketChannel client = srv.accept(); 
    
        // UNIX line endings
        String response = "Hello!\n";
    
        // write encoded data to SocketChannel
        client.write(enc.encode(CharBuffer.wrap(response)));
    
        // close connection
        client.close();
      }
    }
    

    The InetSocketAddress may vary depending on what you're connecting to.

    Deepak : Thanks John, Thanks for your support yhis is one of the excellent program. My mistake was I didi not use "\n" at the end of my string...
    John T : Be careful, it is platform dependent.
    Deepak : Hi John Can u mention on which platform socket channel does not work.
    John T : By platform dependent I was referring to the newline "\n". If you would like a platform independent solution you can use System.getProperty("line.separator")
    Deepak : Hi John how to know whether the client is disconnected before writing to the socket channel

0 comments:

Post a Comment