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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.