how to write data to socket channel

前端 未结 1 424
执笔经年
执笔经年 2021-01-13 07:07

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 rea

相关标签:
1条回答
  • 2021-01-13 07:46

    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.

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