In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to implement a group chat system based on Java based on NIO". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to implement a group chat system based on Java based on NIO".
The details are as follows
Example requirements:
1. Write a NIO group chat system to realize simple data communication between server and client (non-blocking).
two。 Realize multi-group chat
3. Server side: can monitor users online, offline, and achieve message forwarding function
4. Client: through Channel, messages can be sent to all other users without blocking, and messages sent by other users can be accepted (forwarded by the server).
5. Objective: to further understand the programming mechanism of NIO non-blocking network
6. Schematic analysis and code
/ / Server:
Package com.atguigu.nio.groupchat;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.Channel;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.util.Iterator;public class GroupChatServer {/ / definition attribute private Selector selector; private ServerSocketChannel listenChannel; private static final int PORT = 6667 / / Constructor / / initialize work public GroupChatServer () {try {/ / get selector selector = Selector.open (); / / ServerSocketChannel listenChannel = ServerSocketChannel.open (); / / bind port listenChannel.socket () .bind (new InetSocketAddress (PORT)) / / set nonblocking mode listenChannel.configureBlocking (false); / / register the listenChannel with selector listenChannel.register (selector, SelectionKey.OP_ACCEPT);} catch (IOException e) {e.printStackTrace () }} public void listen () {try {/ / Loop processing while (true) {int count = selector.select (); if (count > 0) {/ / have event handling / / traverse to get the selectionKey collection Iterator iterator = selector.selectedKeys (). Iterator () While (iterator.hasNext ()) {/ / take out selectionkey SelectionKey key = iterator.next (); / / listen to accept if (key.isAcceptable ()) {SocketChannel sc = listenChannel.accept () Sc.configureBlocking (false); / / register the sc with seletor sc.register (selector, SelectionKey.OP_READ); / / prompt System.out.println (sc.getRemoteAddress () + "online") } if (key.isReadable ()) {/ / Channel sends read events, that is, the channel is readable / / handles reading (special write method..) ReadData (key);} / / current key deletion to prevent repeated processing of iterator.remove ();}} else {System.out.println ("wait....") } catch (Exception e) {e.printStackTrace ();} finally {/ / exception handling. }} / / read client message public void readData (SelectionKey key) {SocketChannel channel = null; try {/ / get channel channel = (SocketChannel) key.channel (); / / create buffer ByteBuffer buffer = ByteBuffer.allocate (1024); int count = channel.read (buffer) / / process if according to the value of count (count > 0) {/ / convert the cache data into the string String msg = new String (buffer.array ()); / / output the message System.out.println ("form client:" + msg) / / forward messages to other clients (get rid of yourself) and write a special method to handle sendInfoToOtherClients (msg, channel);}} catch (IOException e) {try {System.out.println (channel.getRemoteAddress () + "offline.") / / Unregister key.cancel (); / / close the channel channel.close ();} catch (IOException e2) {e2.printStackTrace () } / / forward messages to other customers (channels) private void sendInfoToOtherClients (String msg, SocketChannel self) throws IOException {System.out.println ("Server forwarding messages...") / / iterate through all SocketChannel registered to selector and exclude self for (SelectionKey key: selector.keys ()) {/ / retrieve the corresponding SocketChannel Channel targetChannel = key.channel () through key; / / exclude your own if (targetChannel instanceof SocketChannel & & targetChannel! = self) {/ / transition SocketChannel dest = (SocketChannel) targetChannel / / Storage msg to buffer ByteBuffer buffer = ByteBuffer.wrap (msg.getBytes ()); / / write buffer data to channel dest.write (buffer);} public static void main (String [] args) {/ / create server object GroupChatServer groupChatServer = new GroupChatServer () GroupChatServer.listen ();}}
/ / client:
Package com.atguigu.nio.groupchat;~~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.SocketChannel;import java.util.Iterator;import java.util.Scanner;public class GroupChatClient {/ / define the related attribute private final String HOST = "127.0.0.1"; / / ip private final int PORT of the server = 6667 / port private Selector selector Private SocketChannel socketChannel; private String username; / / constructor, complete initialization work public GroupChatClient () throws IOException {selector = Selector.open (); / / connect server socketChannel = SocketChannel.open (new InetSocketAddress (HOST, PORT)); / / set non-blocking socketChannel.configureBlocking (false); / / register channel with selector socketChannel.register (selector, SelectionKey.OP_READ) / / get username username = socketChannel.getLocalAddress (). ToString (). Substring (1); System.out.println (username + "is ok...");} / / send a message to the server public void sendInfo (String info) {info = username + "say:" + info; try {socketChannel.write (ByteBuffer.wrap (info.getBytes () } catch (IOException e) {e.printStackTrace ();}} / / read the message public void readInfo () {try {int readChannels = selector.select (); if (readChannels > 0) {/ / there is an available channel Iterator iterator = selector.selectedKeys (). Iterator () While (iterator.hasNext ()) {SelectionKey key = iterator.next (); if (key.isReadable ()) {/ / get the related channel SocketChannel sc = (SocketChannel) key.channel () / / get a Buffer ByteBuffer buffer = ByteBuffer.allocate (1024); / / read sc.read (buffer); / / convert the data of the read buffer into the string String msg = new String (buffer.array ()) System.out.println (msg.trim ());}} iterator.remove (); / / Delete the current selectionKey to prevent repeated operations} else {/ / System.out.println ("No channels available...") }} catch (Exception e) {e.printStackTrace ();}} public static void main (String [] args) throws Exception {/ / launch our client GroupChatClient chatClient = new GroupChatClient () / / start a thread of 3 seconds each to read data sent from the server new Thread () {public void run () {while (true) {chatClient.readInfo (); try {Thread.currentThread () .sleep (3000) } catch (InterruptedException e) {e.printStackTrace ();} .start (); / / send data to the server Scanner scanner = new Scanner (System.in); while (scanner.hasNextLine ()) {String s = scanner.nextLine () ChatClient.sendInfo (s);}}
Running result
The above is all the contents of the article "how to implement a group chat system based on Java based on NIO". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.