In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces Java NIO how to achieve chat room function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
The details are as follows
The code already contains the necessary comments, which are not detailed here. The basic chat room function is realized.
Constant class:
Public class Constant {public static final int serverPort = 44444;}
Server:
Package server; import java.io.IOException;import java.net.InetSocketAddress;import java.net.SocketAddress;import java.nio.ByteBuffer;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.Charset;import java.util.Iterator;import java.util.Set; import constant.Constant; public class SocketServer {private Charset charset = Charset.forName ("UTF-8"); private ServerSocketChannel serverSocketChannel Private Selector serverSocketSelector; private SelectionKey serverRegisterKey; private ByteBuffer buffer = ByteBuffer.allocate (1024); public static void main (String [] args) throws IOException {new SocketServer (). OpenServer (new InetSocketAddress (Constant.serverPort));} public void openServer (SocketAddress address) throws IOException {init (address); handle ();} private void init (SocketAddress address) throws IOException {serverSocketSelector = Selector.open (); serverSocketChannel = ServerSocketChannel.open () ServerSocketChannel.configureBlocking (false); serverRegisterKey = serverSocketChannel.register (serverSocketSelector, SelectionKey.OP_ACCEPT); serverSocketChannel.socket (). Bind (address);} private void handle () throws IOException {System.out.println ("server open"); while (serverSocketSelector.select () > 0) {Iterator iterator = serverSocketSelector.selectedKeys (). Iterator () / / Why are iterators used here instead of enhancing for loops and the like? This is because after a key is obtained here, it needs to be removed to avoid secondary processing, which will affect while (iterator.hasNext ()) {dispatch (iterator.next ()); iterator.remove ();}} private void dispatch (SelectionKey key) throws IOException {if (key.isAcceptable ()) {accept (key). } else if (key.isReadable ()) {readMessage (key);} else if (key.isValid () & & key.isWritable ()) {writeMessage (key) }} private void accept (SelectionKey key) throws IOException, ClosedChannelException {/ / the main thing is that the receiving event occurs on the server side, so the channel on this side should be strongly changed to ServerSocketChannel ServerSocketChannel server = (ServerSocketChannel) key.channel (); SocketChannel client = server.accept (); client.configureBlocking (false) / / register the selector for the channel at the same time, and read client.register (serverSocketSelector, SelectionKey.OP_READ) of the listening content;} private void readMessage (SelectionKey key) throws IOException {SocketChannel client = (SocketChannel) key.channel (); client.read (buffer); / / adjust to read mode buffer.flip (); String content = charset.decode (buffer). ToString () / / compressed space, that is, discard the content that has been read (actually still in it, just waiting to be overwritten) buffer.compact () / / according to the business logic, you can set whether or not to set it, but if you want to reply to a message immediately after receiving the message, set the next interesting (monitoring) event to write key.interestOps (SelectionKey.OP_WRITE); / / set the system reply message key.attach ("the system has received your message\ n") / / start broadcasting the contents of this client to other clients broadcast (key, content);} private void broadcast (SelectionKey self, String content) throws IOException {Set selectedKeys = self.selector () .keys () For (SelectionKey key: selectedKeys) {/ / cannot be sent to yourself, nor should the server itself react to this if (key! = self & & key! = serverRegisterKey) {String oldMessage = (String) key.attach (null) / / if there is an old message, send key.attach (oldMessage! = null?) together with the old message on the next send. OldMessage + content: content); key.interestOps (key.interestOps () | SelectionKey.OP_WRITE);} private void writeMessage (SelectionKey key) throws IOException {SocketChannel client = (SocketChannel) key.channel (); / / get the message sent to this client and empty the message client.write (charset.encode ((String) key.attach (null) Key.interestOps (SelectionKey.OP_READ);}}
Client (including Socket version and SocketChannel version):
Package client; import java.io.IOException;import java.net.InetSocketAddress;import java.net.Socket;import java.net.UnknownHostException;import java.nio.ByteBuffer;import java.nio.channels.SocketChannel;import java.nio.charset.Charset;import java.util.Scanner; import constant.Constant; public class SocketClient {public static void main (String [] args) throws IOException {nioVersion (); / / ioVersion () } private static void ioVersion () throws UnknownHostException, IOException {System.out.println ("client"); final Socket socket = new Socket (); socket.connect (new InetSocketAddress (Constant.serverPort)); new Thread () {@ Override public void run () {Scanner scanner = new Scanner (System.in) While (scanner.hasNext ()) {String line = scanner.nextLine (); try {socket.getOutputStream () .write ((line + "\ n") .getBytes ("UTF-8"));} catch (IOException e) {e.printStackTrace () }} scanner.close (); try {socket.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} }. Start (); new Thread () {@ Override public void run () {try {Scanner scanner = new Scanner (socket.getInputStream (), "utf-8"); while (scanner.hasNext ()) {String line = scanner.nextLine () System.out.println ("received message:" + line);} scanner.close ();} catch (IOException e) {e.printStackTrace ();} .start () } private static void nioVersion () throws IOException {Charset charset = Charset.forName ("UTF-8"); System.out.println ("client"); SocketChannel socketChannel = SocketChannel.open (); / / set to non-blocking mode socketChannel.configureBlocking (false); socketChannel.connect (new InetSocketAddress (Constant.serverPort)) While (true) {if (socketChannel.finishConnect ()) {new Thread () {@ Override public void run () {Scanner scanner = new Scanner (System.in) While (scanner.hasNext ()) {String input = scanner.nextLine (); try {socketChannel.write (charset.encode (input)) } catch (IOException e) {e.printStackTrace ();}} scanner.close ();}. Start () New Thread () {ByteBuffer dst = ByteBuffer.allocate (1024); @ Override public void run () {while (true) {try {int len = socketChannel.read (dst) If (len > 0) {dst.flip (); System.out.println ("received message:" + charset.decode (dst)); dst.compact () }} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () Start (); return Thank you for reading this article carefully. I hope the article "how to realize the chat room function of Java NIO" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.