Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write data to socket channel

Tags:

java

nio

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

like image 475
Deepak Avatar asked May 16 '09 07:05

Deepak


1 Answers

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.

like image 146
John T Avatar answered Oct 16 '22 19:10

John T