Server side:
Package Niot;
Import java.io.IOException;
Import java.net.InetSocketAddress;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.SelectionKey;
Import Java.nio.channels.Selector;
Import Java.nio.channels.ServerSocketChannel;
Import Java.nio.channels.SocketChannel;
Import Java.nio.charset.Charset;
Import Java.util.Iterator;
public class NIOServer1 {//local character set private static final String Localcharsetname = "UTF-8";
The port on which the local server listens private static final int listenning_port = 8888;
Buffer size private static final int buffer_size = 1024;
Timeout, unit milliseconds private static final int TimeOut = 3000; public static void Main (string[] args) throws IOException {//Creates a service socket channel that listens on the local port. and set to non-blocking mode Serversocketchannel
Serverchannel = Serversocketchannel.open ();
Serverchannel.socket (). bind (New Inetsocketaddress (Listenning_port));
Serverchannel.configureblocking (FALSE);
Create a selector and register the serverchannel above it Selector Selector = Selector.open (); Serverchannel.register (Selector, SelectionKey.op_accept);
while (true) {//waits for a channel ready if (Selector.select (TimeOut) = = 0) {System.out.println (".");
Continue
}//Get the key iterator for the ready channel iterator<selectionkey> keyiter = Selector.selectedkeys (). iterator ();
Use iterators to traverse the Ready channel while (Keyiter.hasnext ()) {Selectionkey key = Keyiter.next (); This situation is a client-side connection to prepare a clientchannel with which the communication if (Key.isacceptable ()) {Socketchannel Clientchannel = (Serversocketchan
Nel) key.channel ()). Accept ();
Clientchannel.configureblocking (FALSE);
Clientchannel.register (selector, Selectionkey.op_read, Bytebuffer.allocate (buffer_size)); ////client has write-time if (key.isreadable ()) {//access channel Socketchannel Clientchannel = (socketchannel) key.c
Hannel ();
The main index value of the reset buffer is obtained bytebuffer buffer = (bytebuffer) key.attachment ();
Buffer.clear ();
Read the number of bytes read to get a long bytesread = clientchannel.read (buffer); if (bytesread = = 1) {//no content is read ClientchAnnel.close ();
else {//prepare buffer as data outgoing state buffer.flip (); Gets the byte string (decoded using Charset) string receivedstring = Charset. forname (Localcharsetname). Newdecoder (). Decode (BU
Ffer). toString ();
The console prints out SYSTEM.OUT.PRINTLN ("Receive information:" + receivedstring); Ready to send the text String sendstring = "Hello, client."
Have received your message "+ receivedstring;
The string encoding to be sent (encoded using charset) is then wrapped buffer = Bytebuffer.wrap (Sendstring.getbytes (localcharsetname));
Send back Clientchannel.write (buffer); Set to prepare for next read or write Key.interestops (Selectionkey.op_read |
Selectionkey.op_write);
} keyiter.remove ();
}
}
}
}
Client:
Package Niot;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import Java.util.Scanner;
public class Nioclient1test {public
static void Main (string[] args) throws Unknownhostexception,
IOException { C10/>socket s = new Socket ("localhost", 8888);
InputStream instream = S.getinputstream ();
OutputStream OutStream = S.getoutputstream ();
Output
PrintWriter out = new PrintWriter (OutStream, true);
Out.println ("Getpublickey hello.") ");
Out.flush ();
S.shutdownoutput ()//Output end
//input
Scanner in = new Scanner (instream);
StringBuilder sb = new StringBuilder ();
while (In.hasnextline ()) {
String line = In.nextline ();
Sb.append (line);
String response = sb.tostring ();
System.out.println ("response=" + response);
}
Run results
Service side:
.
Received information: Getpublickey hello.
.
Client:
response= Hello, client. have received your message Getpublickey hello.