Socket asynchronous naga instance details

Source: Internet
Author: User

This article describes how to use Socket asynchronous naga instances. I hope this tutorial will be helpful to you.

The naga project was recommended by others on Stack Overflow. I just wrote something simple. I tried it when I saw that the pseudocode on the project homepage was quite concise.

The Code is as follows: Copy code

NIOService service = new NIOService;
NIOServerSocket serverSocket = service. openServerSocket (1234 );
ServerSocket. setConnectionAcceptor (myAcceptor );
ServerSocket. listen (myObserver );
NIOService service = new NIOService;
NIOSocket serverSocket = service. openSocket (www.bkjia. c0m, 1234 );
Socket. listen (myObserver );
// Asynchronous write by default:
Socket. write ("Some message". getBytes ());

The code is quite simple, so it won't be too long. It is transformed from the official DEMO code.

As shown in the pseudo-code example, you only need to add a ServerSocketObserverAdapter to the socket listener.

The Code is as follows: Copy code

Package com. socket. naga;
 
Import java. io. ByteArrayInputStream;
Import java. io. ByteArrayOutputStream;
Import java. io. DataInputStream;
Import java. io. DataOutputStream;
Import java. io. IOException;
Import java. util. HashMap;
Import java. util. Map;
 
Import naga. ConnectionAcceptor;
Import naga. NIOServerSocket;
Import naga. NIOService;
Import naga. NIOSocket;
Import naga. ServerSocketObserverAdapter;
Import naga. SocketObserverAdapter;
Import naga. packetreader. RegularPacketReader;
Import naga. packetwriter. RegularPacketWriter;
 
Public class ValidationServer {
Private NIOService service;
Private NIOServerSocket socket;
 
Public ValidationServer () throws IOException {
Service = new NIOService ();
}
 
Public void start () throws IOException {
Int port = 9001;
Socket = service. openServerSocket (port );
Final Map <String, String> passwords = new HashMap <String, String> ();
Passwords. put ("Admin", "password ");
Passwords. put ("Aaron", "AAAAAAAA ");
Passwords. put ("Bob", "QWERTY ");
Passwords. put ("Lisa", "secret ");
 
Socket. listen (new ServerSocketObserverAdapter (){
Public void newConnection (NIOSocket nioSocket ){
System. out. println ("Received connection:" + nioSocket );
 
NioSocket. setPacketReader (new RegularPacketReader (1, true ));
 
NioSocket. setPacketWriter (new RegularPacketWriter (1, true ));
 
NioSocket. listen (new SocketObserverAdapter (){
Public void packetReceived (NIOSocket socket, byte [] packet ){
System. out. println ("Login attempt from" + socket );
Try {
DataInputStream stream = new DataInputStream (new ByteArrayInputStream (packet ));
 
String user = stream. readUTF ();
String password = stream. readUTF ();
 
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ();
DataOutputStream out = new DataOutputStream (byteArrayOutputStream );
 
If (! Passwords. containsKey (user )){
System. out. println ("Unknown user:" + user );
Out. writeUTF ("NO_SUCH_USER ");
} Else if (! Passwords. get (user). equals (password )){
Out. writeUTF ("INCORRECT_PASS ");
System. out. println ("Failed login for:" + user );
} Else {
Out. writeUTF (user + "LOGIN_ OK ");
System. out. println ("Successful login for:" + user );
}
 
Out. flush ();
Socket. write (byteArrayOutputStream. toByteArray ());
 
Socket. closeAfterWrite ();
} Catch (IOException e ){
Socket. close ();
}
}
});
}
 
});
Socket. setConnectionAcceptor (ConnectionAcceptor. ALLOW );
 
While (true ){
Service. selectBlocking ();
}
}
 
Public void close (){
If (socket. isOpen ())
Socket. close ();
 
If (service. isOpen ())
Service. close ();
}
 
Public static void main (String [] args ){
Try {
ValidationServer validationServer = new ValidationServer ();
ValidationServer. start ();
// ValidationServer. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
}

The client adds SocketObserver to the listener.

The Code is as follows: Copy code
Package com. socket. naga;
 
Import java. io. ByteArrayInputStream;
Import java. io. ByteArrayOutputStream;
Import java. io. DataInputStream;
Import java. io. DataOutputStream;
Import java. io. IOException;
Import java. util. HashMap;
Import java. util. Map;
Import java. util. Map. Entry;
 
Import naga. NIOService;
Import naga. NIOSocket;
Import naga. SocketObserver;
Import naga. packetreader. RegularPacketReader;
Import naga. packetwriter. RegularPacketWriter;
 
Public class ValidationClient {
Private NIOService service;
Private NIOSocket socket;
 
Public ValidationClient () throws IOException {
Service = new NIOService ();
}
 
Public void send (final String account, final String password) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream ();
DataOutputStream dataStream = new DataOutputStream (stream );
DataStream. writeUTF (account );
DataStream. writeUTF (password );
DataStream. flush ();
Final byte [] content = stream. toByteArray ();
DataStream. close ();
 
Socket = service. openSocket ("127.0.0.1", 9001 );
Socket. setPacketReader (new RegularPacketReader (1, true ));
Socket. setPacketWriter (new RegularPacketWriter (1, true ));
 
// Start listening to the socket.
Socket. listen (new SocketObserver (){
Public void connectionOpened (NIOSocket nioSocket ){
System. out. println ("Sending login..." + account + "//" + password );
NioSocket. write (content );
}
 
Public void packetReceived (NIOSocket socket, byte [] packet ){
Try {
// Read the UTF-reply and print it.
String reply = new DataInputStream (new ByteArrayInputStream (packet). readUTF ();
System. out. println ("Reply was:" + reply );
} Catch (Exception e ){
// E. printStackTrace ();
}
}
 
Public void connectionBroken (NIOSocket nioSocket, Exception exception ){
System. out. println ("Connection failed." + nioSocket. isOpen () + "" + exception. getMessage ());
}
});
 
While (true) {// wait
Service. selectBlocking ();
}
}
 
Public static void main (String [] args) throws IOException {
Final Map <String, String> passwords = new HashMap <String, String> ();
Passwords. put ("Admin", "password ");
Passwords. put ("Aaron", "AAAAAAAA ");
Passwords. put ("Bob", "QWERTY ");
Passwords. put ("Lisa", "secret ");
 
ValidationClient client = new ValidationClient ();
For (Entry <String, String> pasword: passwords. entrySet ()){
Client. send (pasword. getKey (), pasword. getValue ());
}
// Client. stop ();
}
}

It is not as good as Netty's design and not as elegant as it is in terms of details. It is quite good to write a demo.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.