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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With