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 simple chat Program with java NIO

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

Share

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

This article mainly shows you "java NIO how to achieve a simple chat program", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to achieve simple chat program java NIO" this article.

The details are as follows

Server side

Features:

1. Accept client connections

2. Send messages

3. Read client messages

Server.java

Public class Server {private Selector selector; private ByteBuffer writeBuffer = ByteBuffer.allocate (1024); private ByteBuffer readBuffer = ByteBuffer.allocate (1024); Msg msg = new Msg (); MsgSender msgSender = new MsgSender (msg); public static void main (String [] args) {Server server = new Server (); new Thread (server.msgSender). Start (); server.start () } / / initialize server public Server () {try {this.selector = Selector.open (); ServerSocketChannel ssc = ServerSocketChannel.open (); ssc.configureBlocking (false); ssc.bind (new InetSocketAddress (8899)); ssc.register (this.selector, SelectionKey.OP_ACCEPT) System.out.println ("server initialization completed.") ;} catch (IOException e) {e.printStackTrace ();}} / start the server to wait for the selector event public void start () {while (true) {try {int num = this.selector.select () If (num > 0) {Iterator it = this.selector.selectedKeys () .iterator (); while (it.hasNext ()) {SelectionKey key = it.next (); it.remove () If (key.isValid ()) {if (key.isAcceptable ()) {this.accept (key);} if (key.isReadable ()) {this.read (key) } if (key.isWritable ()) {this.write (key) }} catch (IOException e) {e.printStackTrace ();} / / send the message private void write (SelectionKey key) {SocketChannel sc = (SocketChannel) key.channel () Try {sc.configureBlocking (false);} catch (IOException e) {e.printStackTrace ();} / / determine whether a message needs to be sent if (msgmessages) {System.out.println (msg); try {msg.setFlag (false); writeBuffer.clear () WriteBuffer.put (msg.getContent (). GetBytes ()); writeBuffer.flip (); sc.write (writeBuffer);} catch (IOException e) {e.printStackTrace () Read client messages private void read (SelectionKey key) {SocketChannel sc = (SocketChannel) key.channel (); try {sc.configureBlocking (false); readBuffer.clear (); int read = sc.read (readBuffer); if (read = =-1) {sc.close () Key.cancel ();} readBuffer.flip (); System.out.println (new String (readBuffer.array ();} catch (IOException e) {e.printStackTrace ();}} / / accept client connection private void accept (SelectionKey key) {ServerSocketChannel ssc = (ServerSocketChannel) key.channel () Try {SocketChannel sc = ssc.accept (); System.out.println (String.format ("a new client jointed joint hostlass% sportscape% d", sc.socket (). GetLocalAddress (), sc.socket (). GetPort ()); sc.configureBlocking (false); sc.register (this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE) } catch (IOException e) {e.printStackTrace ();}

Msg.java

Class Msg {private Boolean flag=false; private String content; public Boolean getFlag () {return flag;} public void setFlag (Boolean flag) {this.flag = flag;} public String getContent () {return content;} public void setContent (String content) {this.content = content } @ Override public String toString () {return "Msg {" + "flag=" + flag + ", content='" + content +'\'+'}';}}

MsgSender.java

Class MsgSender implements Runnable {private Msg msg; public MsgSender (Msg msg) {this.msg = msg;} @ Override public void run () {while (true) {System.out.println ("input:\ n"); Scanner scanner = new Scanner (System.in); this.msg.setContent (scanner.next ()); this.msg.setFlag (true) } client

When using BIO, it simply uses threads to read and write messages.

Features:

1. Connect the server

2. Read messages

3. Send messages

Public class Client {private SocketChannel sc; ByteBuffer writeBuffer = ByteBuffer.allocate (1024); ByteBuffer readBuffer = ByteBuffer.allocate (1024); public static void main (String [] args) {new Client ();} public Client () {try {sc = SocketChannel.open (); / / Connect server sc.connect (new InetSocketAddress (8899)) / / send message this.write (sc); / / read message this.read (sc);} catch (IOException e) {e.printStackTrace () }} private void read (SocketChannel sc) {new Thread (new Runnable () {@ Override public void run () {while (true) {try {readBuffer.clear (); int read = sc.read (readBuffer)) ReadBuffer.flip (); System.out.println (new String (readBuffer.array ();} catch (IOException e) {e.printStackTrace ();}) .start () } private void write (SocketChannel sc) {new Thread (new Runnable () {@ Override public void run () {while (true) {Scanner scanner = new Scanner (System.in); String next = scanner.next (); writeBuffer.clear () WriteBuffer.put (next.getBytes ()); writeBuffer.flip (); try {sc.write (writeBuffer);} catch (IOException e) {e.printStackTrace () }). Start ();}} these are all the contents of the article "how to implement a simple chat program in java 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.

Share To

Development

Wechat

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

12
Report