Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Group chat Mode in java based on NIO

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how java implements group chat mode based on NIO. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

The details are as follows

Client

Package com.qst.chat;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 {private final int PORT = 9999; private final String HOST = "localhost"; private SocketChannel channel; private static Selector selector; private String name; public GroupChatClient () throws IOException {selector = Selector.open () / / Connect server channel = SocketChannel.open (new InetSocketAddress (HOST, PORT)); / / set non-blocking channel.configureBlocking (false); / / register channel with selector channel.register (selector, SelectionKey.OP_READ); name = channel.getLocalAddress (). ToString (). Substring (1); System.out.println (name + "is ok....") } / / send the message public void sendTO (String msg) {ByteBuffer buffer = ByteBuffer.wrap ((name+ ":" + msg). GetBytes ()); try {channel.write (buffer);} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () }} / / read the message public static void getInfo () {try {if (selector.select () > 0) {Iterator iterator = selector.selectedKeys () .iterator (); while (iterator.hasNext ()) {SelectionKey key = iterator.next (); if (key.isReadable ()) {/ / get the channel SocketChannel sc = (SocketChannel) key.channel () ByteBuffer buffer = ByteBuffer.allocate (1024); int len; / / converts the data of the read buffer into the string while ((len = sc.read (buffer)) > 0) {System.out.println (new String (buffer.array ();} / / deletes the current selectionKey to prevent repetitive operation iterator.remove () }} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} public static void main (String [] args) {try {GroupChatClient client = new GroupChatClient (); new Thread () {public void run () {while (true) {try {Thread.sleep (3000); GroupChatClient.getInfo () } catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace ();};} .start (); Scanner sc = new Scanner (System.in); / / while (true) {/ / String name = sc.nextLine (); / / client.sendTO (name); / /} while (sc.hasNextLine ()) {String s = sc.nextLine () Client.sendTO (s);}} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}

Server end

Package com.qst.chat;import java.io.IOException;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;import java.nio.ByteBuffer;import java.nio.channels.SelectableChannel;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.time.chrono.IsoChronology;import java.util.Iterator;import com.sun.accessibility.internal.resources.accessibility;import sun.print.resources.serviceui Public class GroupChatServer {private static ServerSocketChannel socketChannel; private static Socket socket; private static Selector selector; private static SocketChannel accept; public GroupChatServer () throws IOException {socketChannel = ServerSocketChannel.open (); selector = Selector.open (); / / bind port socketChannel.socket () .bind (new InetSocketAddress (9999)); / / set non-blocking mode socketChannel.configureBlocking (false); / / register the channel with selector socketChannel.register (selector, SelectionKey.OP_ACCEPT) } / / listen to public static void listen () {System.out.println ("listening thread:" + Thread.currentThread (). GetName ()); try {while (selector.select () > 0) {Iterator iterator = selector.selectedKeys () .iterator (); if (iterator.hasNext ()) {/ / traverse to get the selectionKey collection SelectionKey next = iterator.next (); if (next.isAcceptable ()) {next.channel () / / socketChannel = (ServerSocketChannel) next.channel (); SocketChannel accept = socketChannel.accept (); accept.configureBlocking (false); accept.register (selector, SelectionKey.OP_READ); System.out.println (accept.getRemoteAddress () + "online.") ;} if (next.isReadable ()) {readDate (next);} / / remove the current next to prevent repeated processing of iterator.remove (); / / System.out.println ("not found");}} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () }} / / read client messages public static void readDate (SelectionKey key) {try {accept = (SocketChannel) key.channel (); ByteBuffer buffer = ByteBuffer.allocate (1024); int len = accept.read (buffer); if (len > 0) {buffer.flip (); String msg = new String (buffer.array ()); System.out.println ("user =" + msg) / / forward messages to other clients (remove yourself) sendToAll (msg, accept); buffer.clear ();}} catch (IOException e) {/ / TODO Auto-generated catch block try {String msg = accept.getRemoteAddress (). ToString (); / unregister key.cancel (); / / close channel accept.close (); System.out.println (msg + "offline") } catch (IOException E1) {/ / TODO Auto-generated catch block e1.printStackTrace ();} / / e.printStackTrace ();} finally {/ / TODO: handle finally clause}} public static void sendToAll (String msg, SocketChannel ssc) {for (SelectionKey ss: selector.keys ()) {/ / fetch the corresponding SocketChannel SelectableChannel channel = ss.channel () through key / / exclude yourself from if (channel instanceof SocketChannel & & channel! = ssc) {/ / transition SocketChannel sh = (SocketChannel) channel; / / transfer to buffer ByteBuffer wrap = ByteBuffer.wrap (msg.getBytes ()); try {/ / write channel sh.write (wrap);} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () Public static void main (String [] args) throws IOException {GroupChatServer server = new GroupChatServer (); GroupChatServer.listen ();}}

When key.isAcceptable () accesses, there are two ways to get the channel.

1. Get (Selector key) socketChannel = (ServerSocketChannel) key.channel () through selector

Establish a connection to socketChannel. Accept ()

2. Define a global variable

When initializing, store (socketChannel = ServerSocketChannel.open ();)

Establish a connection to socketChannel. Accept ()

Key.isReadable () when reading in () SelectionKey key accept = (SocketChannel) key.channel ()

Demo

Server startup, client startup

The client sends messages

Start the second client

The two clients communicate with each other

Offline information display

This is the end of the article on "how to implement group chat mode based on java based on NIO". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report