Fundamentals of Java Network Programming (vi)-NIO simple chat system based on TCP

Source: Internet
Author: User

In the Java Network Programming Foundation (iv), it is mentioned that the simple chat system of the TCP/IP simple chat system based on socket realizes a multi-client Dharma message. The server uses multithreading to handle the message sending of multiple clients and forwards it to the target user. But because it is socket-based, it is blocked.

In this section we will use Socketchannel and serversocketchannel to achieve the same functionality.

1. Format of client input message

Username:msg username represents the user name to be sent, MSG is the sending content, separated by a colon

2. Realization of Ideas

The realization idea is similar to the realization idea of Java Network Programming Foundation (iv), the server needs to keep a list of user names so that the corresponding users can be found when the message is forwarded. For the client, the client needs to be able to receive messages forwarded from the server at any time, and can send messages via keyboard input at any time.

3. Realization Process

Based on these ideas, the client needs to have a separate thread, so it needs to implement 3 classes

(1) Client main program Chatclient.java

The program is responsible for starting the client child thread, based on the user name parameter entered at startup, to establish a connection to the server by a sub-thread. In the main thread, you need to loop through the input of the keyboard, send the incoming message through the Cheng to the server, and forward the message to the client by the server.

(2) Client child thread Clientthread.java

This thread encapsulates all operations on the client and server side

A, in the constructor, based on the creation of a connection to the server

b, in the main function of the thread to establish a connection event with the server, send the user name to the servers to register, in the format: Username = XXX (startup parameters)

c, Send message function: The external main thread after receiving the keyboard input, call the function to send a message to the server, the message format is "To:content" (that is, username:message), in order to the server can distinguish who sent to the user, User name Usename needs to be added as well. From:to:content

D, close function: Turn off client-server connectivity after the client enters the bye command

(3) Server main program Chatserver.java

This class is responsible for starting the server, and is responsible for listening to the client's requests, and is responsible for processing the client's input/output and message forwarding tasks, and therefore contains the following features

A. Start the server and listen for client connections

B, when reading a message sent by the client with the word "username = XXX", represents the first connection established by the client and adds the user to the list of clients

C, read the client input data, the message format is similar to "From:to:content", the first colon ":" Before the section is the sender user name, the second colon before the part of the recipient user name, the last part of the message content. The client is found in the client list based on the recipient user name, and the data is sent to the client.

"Service-side Code"

Package org.test.nio.chat;import java.io.ioexception;import java.net.inetsocketaddress;import  java.nio.bytebuffer;import java.nio.charbuffer;import java.nio.channels.closedchannelexception ;import java.nio.channels.selectionkey;import java.nio.channels.selector;import  java.nio.channels.serversocketchannel;import java.nio.channels.socketchannel;import  java.nio.charset.charactercodingexception;import java.nio.charset.charset;import  java.nio.charset.charsetdecoder;import java.nio.charset.charsetencoder;import java.util.hashtable; Import java.util.iterator;public class chatserver {public static void main ( String[] args)  {//  Client list hashtable<string, socketchannel> clietlist =  New hashtable<string, socketchannel> (); selector selector = null; serversocketchannel server = null;try {//  Create a SelectorSelector = selector.open ();//  create socket and register Server = serversocketchannel.open (); Server.configureblocking (false); Server.register (selector, selectionkey.op_accept);//  Start the Listening port inetsocketaddress ip = new inetsocketaddress (12345); Server.socket (). bind (IP); SYSTEM.OUT.PRINTLN ("Start server successfully!"); / todo  Listener Event while  (true)  {//  Listener Event Selector.select ();//  Event Source list iterator< Selectionkey> it = selector.selectedkeys (). Iterator ();while  (It.hasnext ())  { Selectionkey key = it.next ();//  Delete the event it.remove ();//  Determine the event type if  (Key.isAcceptable () )  {//  Connection Event serversocketchannel server2 =  (Serversocketchannel)  key.channel (); Socketchannel channel = server2.accept (); channel.configureblocking (false);if  ( Channel.isconnectionpending ())  {channel.finishconnect ();} Channel.register (Selector, selectionkey.op_read); SYSTEM.OUT.PRINTLN ("Client connection:"  + channel.socket (). Getinetaddress (). GetHostName () + channel.socket (). Getport ());}  else if  (Key.isreadable ())  {//  read Data event socketchannel channel =  ( Socketchannel)  key.channel ();//  read Data charsetdecoder decoder = charset.forname ("UTF-8") . Newdecoder (); Bytebuffer buffer = bytebuffer.allocate (+); channel.read (buffer); Buffer.flip (); String msg = decoder.decode (buffer). toString (); System.out.println ("Received:"  + msg); if (Msg.startswith ("Username=") {string username =  Msg.replaceall ("username=",  "); Clietlist.put (Username, channel);} else{//forwards the message to the client String[] arr = msg.split (":"); if (arr.length == 3) {String from  = arr[0];//Sender string to = arr[1];//Recipient string content = arr[2];// Send content if (Clietlist.containskey (to)) {Charsetencoder encoder = charset.forname ("UTF-8"). NewEncoder ( );//Send Message clietlist to receiver.Get (To). Write (Encoder.encode (Charbuffer.wrap (from+ "" "" +content)));}} else{string from = arr[0]; string content =  "From Server message: You have not specified a recipient"; Charsetencoder encoder = charset.forname ("UTF-8"). Newencoder ();//Send Message Clietlist.get (from) to the receiver. Write (Encoder.encode (charbuffer.wrap (content)));}}}}}  catch  (closedchannelexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  catch  (charactercodingexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  finally{try {selector.close (); Server.close ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}}

         client thread

Package org.test.nio.chat;import java.io.ioexception;import java.net.inetsocketaddress;import  java.nio.bytebuffer;import java.nio.charbuffer;import java.nio.channels.closedchannelexception ;import java.nio.channels.selectionkey;import java.nio.channels.selector;import  java.nio.channels.socketchannel;import java.nio.charset.charactercodingexception;import  java.nio.charset.charset;import java.nio.charset.charsetdecoder;import  java.nio.charset.charsetencoder;import java.util.iterator;public class clientthread  Extends thread {private charsetdecoder decoder = charset.forname ("UTF-8"). Newdecoder ();p rivate charsetencoder encoder = charset.forname ("UTF-8"). NewEncoder (); private selector selector = null;private socketchannel socket = null; Private selectionkey clientkey = null;private string username;// todo  Start Client Public clientthread (string username) {try {//  Create Selectorselector = selector.open ();//  Create and register Socketsocket = socketchannel.open (); Socket.configureblocking (false); Clientkey = socket.register (Selector, selectionkey.op_connect) ;//  Connect to the remote address inetsocketaddress ip = new inetsocketaddress ("localhost",  12345); Socket.connect (IP); this.username = username;}  catch  (closedchannelexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}} @Overridepublic  void run ()  {try {//  Monitor event while  (True)  {selector.select (1);//   Event Source list Iterator<selectionkey> it = selector.selectedkeys (). Iterator ();while  ( It.hasnext ())  {selectionkey key = it.next ();//  Delete Current event it.remove ();//  determine current event type if  (Key.isconnectable ())  {//  Connection Event socketchannel  channel =  (Socketchannel)  key.channel (); if (channel.isconnectionpending ()) {Channel.finishConnect ();} Channel.register (Selector, selectionkey.op_read); SYSTEM.OUT.PRINTLN ("Connection server-side success! ");//Send User name Send (" username= "+this.username);}  else if  (Key.isreadable ())  {//  read Data event socketchannel channel =  ( Socketchannel)  key.channel ();//channel.register (Selector, selectionkey.op_write);//  Read Data bytebuffer buffer = bytebuffer.allocate, channel.read (buffer); Buffer.flip (); String msg = decoder.decode (buffer). toString (); System.out.println ("" Received: " + msg);}}}  catch  (closedchannelexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  catch  (charactercodingexception e)  {// todo auto-generated catch blocKe.printstacktrace ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}} Void send (string msg)  {// TODO  Send Message try {socketchannel channel =  ( Socketchannel)  clientkey.channel (); Channel.write (Encoder.encode (Charbuffer.wrap (msg)));}  catch  (charactercodingexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}  TODO  Close Client Public void close ()  {try {selector.close (); Socket.close ();}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}}

client

Package Org.test.nio.chat;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;public class ChatClient {public static void main (string[] args) {//TODO auto-generated method s tubstring username = args[0]; Clientthread client = new Clientthread (username); Client.start ();//input \ output stream BufferedReader sin = new BufferedReader (new InputStreamReader (system.in)); try {//Loop read keyboard input string Readline;while ((ReadLine = Sin.readline (). Trim ()) = null) {if ( Readline.equals ("Bye")) {client.close (); System.exit (0);} Client.send (username + ":" + ReadLine);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Run results

Service side

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/80/E6/wKioL1dENBDiwo64AABQefYV92Y392.png "title=" capture. PNG "alt=" Wkiol1denbdiwo64aabqefyv92y392.png "/>

Client

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/80/E8/wKiom1dEM1LC1og_AABBDHAq9vo759.png "title=" capture. PNG "alt=" Wkiom1dem1lc1og_aabbdhaq9vo759.png "/>

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/80/E6/wKioL1dENG6BMWjGAAAtGFFjW5s463.png "title=" capture. PNG "alt=" Wkiol1deng6bmwjgaaatgffjw5s463.png "/>

Relatively simple, but really is the specific application of NIO, like please pay attention to



This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1782644

Fundamentals of Java Network Programming (vi)-NIO simple chat system based on TCP

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.