本文实例为大家分享了java nio实现聊天功能的具体代码,供大家参考,具体内容如下
rver code :
package com.tch.test.nio; import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.bytebuffer;import java.nio.channels.clodchannelexception;import java.nio.channels.lectionkey;import java.nio.channels.lector;import java.nio.channels.rversocketchannel;import java.nio.channels.socketchannel;import java.util.arraylist;import java.util.iterator;import java.util.list;import java.util.t; public class niorver { private socketchannel socketchannel = null; private t<lectionkey> lectionkeys = null; private iterator<lectionkey> iterator = null; private iterator<socketchannel> iterator2 = null; private lectionkey lectionkey = null; public static void main(string[] args) { new niorver().start(); } private void start(){ try { //create rversocketchannel rversocketchannel rversocketchannel = rversocketchannel.open(); //bind the rversocketchannel to a port rversocketchannel.bind(new inetsocketaddress(7878)); //when using lector ,should config the blocking mode of rversocketchannel to non-blocking rversocketchannel.configureblocking(fal); //create a lector to manage all the channels lector lector = lector.open(); //reigst the rversocketchannel to the lector(interest in accept event) 行列式的计算方法 rversocketchannel.register(lector, lectionkey.op_accept); //create a list to store all the socketchannels list<socketchannel> clients = new arraylist<socketchannel>(); //create a bytebuffer to store data bytebuffer buffer = bytebuffer.allocate(1024); while(true){ //this method will block until at least one of the interested events is ready int ready = lector.lect(); if(ready > 0){//means at least one of the interested events is ready lectionkeys = lector.lectedkeys(); iterator = lectionkeys.iterator(); while(iterator.hasnext()){ //the lectionkey contains the channel and t一路一带是什么意思he event which the channel is interested in lectionkey = iterator.next(); //accept event , means new client reaches if(lectionkey.isacceptable()){ //handle new client rversocketchannel rversocketchannel2 = (rversocketchannel)lectionkey.channel(); socketchannel = rversocketchannel2.accept(); //when using lector , should config the blocking mode of socketchannel to non-blocking socketchannel.configureblocking(fal); //regist the socketchannel to the lector socketchannel.register(lector, lectionkey.op_read); //add to client list clients.add(socketchannel); }el if(lectionkey.isreadable()){ //read message from client socketchannel = (socketchannel)lectionkey.channel(); buffer.clear(); try { socketchannel.read(buffer); buffer.flip(); //nd message to every client iterator2 = clients.iterator(); socketchannel socketchannel2 = null; while(iterator2.hasnext()){ socketchannel2 = iterator2.next(); while(buffer.hasremaining()){ socketchannel2.write(buffer); } //rewind method makes the buffer ready to the next read operation buffer.rewind(); } } catch (ioexception e) { // ioexception occured on the channel, remove from channel list e.printstacktrace(); // note: clo the channel socketchannel.clo(); iterator2 = clients.iterator(); while(iterator2.hasnext()){ if(socketchannel == iterator2.next()){ // remove the channel iterator2.remove(); system.out.println("remove the clod channel from client list ..."); break; } } } } //important , remember to remove the channel after all the operations. so that the next lector.lect() will //return this channel again . iterator.remove(); } } } } catch (clodchannelexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } }
client code :
package com.tch.nio.test; import java.awt.gridlayout;import java.awt.event.actionevent;import java.awt.event.actionlistener;import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.bytebuffer;import java.nio.channels.lectionkey;import java.nio.channels.lector;import java.nio.channels.socketchannel;import java.util.iterator;import java.util.t; import javax.swing.jbutton;import javax.swing.jframe;import javax.swing.jtextarea;import javax.swing.jtextfield; public class nioclient extends jframe{ private static final long rialversionuid = 1l; private jtextarea area = new jtextarea("content :"); private jtextfield textfield = new jtextfield("textfield:"); private jbutton button = new jbutton("nd"); private socketchannel socketchannel = null; private bytebuffer buffer = bytebuffer.allocate(1024); private bytebuffer buffer2 = bytebuffer.allocate(1024); private string message = null; public static void main(string[] args) throws exception { nioclient client = new nioclient(); client.start(); } private void start() throws ioexception{ tbounds(200, 200, 300, 400); tlayout(new gridlayout(3, 1)); add(area); add(textfield); //create a socketchannel and connect to the specified address socketchannel = socketchannel.open(new inetsocketaddress("localhost", 7878)); //when using lector , should config the blocking mode of socketchannel to non-blocking socketchannel.configureblocking(fal); button.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent event) { try { message = textfield.gettext(); textfield.ttext(""); //nd message to rver buffer.put(message.getbytes("utf-8")); buffer.flip(); while(buffer.hasremaining()){ socketchannel.write(buffer); } buffer.clear(); } catch (exception e) { e.printstacktrace(); } } }); add(button); tdefaultclooperation(exit_on_clo); tvisible(true); t<lectionkey> lectionkeys = null; iterator<lectionkey> iterator = null; lectionkey lectionkey = null; lector lector = lector.open(); //reigst the socketchannel to the lector(interest in read event) socketchannel.register(lector, lectionkey.op_read); while(true){ //this method will block until at least one of the interested events is ready int ready = lector.lect(); if(ready > 0){//means at least one of the interested events is ready lectionkeys = lector.lectedkeys(); iterator = lectionkeys.iterator(); while(iterator.hasnext()){ lectionkey = iterator.next(); //read message from rver ,then append the message to textarea if(lectionkey.isreadable()){ socketchannel.read(buffer2); buffer2.flip(); area.ttext(area.gettext().trim()+"\n"+new string(buffer2.array(),0,buffer2.limit(),"utf-8")); buffer2.clear(); } //important , remember to remove the channel after all the operations. so that the next lector.lect() will //return this channel again . iterator.remove(); } } } } }
run rver first , then is client , type message and nd , ok
使用mina实现聊天:
rver:
package com.tch.test.jms.origin.rver; import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.chart.chart;import java.util.arraylist;import java.util.list; import org.apache.mina.core.rvice.ioacceptor;import org.apache.mina.core.rvice.iohandleradapter;import org.apache.mina.core.ssion.idlestatus;import org.apache.mina.core.ssion.iossion;import org.apache.mina.filter.codec.protocolcodecfilter;import org.apache.mina.filter.codec.textline.textlinecodecfactory;import org.apache.mina.filter.logging.loggingfilter;import org.apache.mina.transport.socket.nio.niosocketacceptor;import org.slf4j.logger;import org.slf4j.loggerfactory; public class myrver { private static final logger logger = loggerfactory.getlogger(myrver.class); private list<iossion> clientssionlist = new arraylist<iossion>(); public static void main(string[] args) { ioacceptor acceptor = new niosocketacceptor(); acceptor.getfilterchain().addlast("logger", new loggingfilter()); acceptor.getfilterchain().addlast("codec", new protocolcodecfilter(new textlinecodecfactory(chart.forname("utf-8")))); acceptor.thandler(new myrver().new myrveriohandler()); try { acceptor.bind(new inetsocketaddress(10000)); } catch (ioexception ex) { logger.error(ex.getmessage(), ex); } } class myrveriohandler extends iohandleradapter{ @override public void ssioncreated(iossion ssion) throws exception { logger.info("ssioncreated"); } @override public void ssionopened(iossion ssion) throws exception { logger.info("ssionopened"); if(! clientssionlist.contains(ssion)){ clientssionlist.add(ssion); } } @override public void ssionclod(iossion ssion) throws exception { logger.info("ssionclod"); clientssionlist.remove(ssion); } @override public void ssionidle(iossion ssion, idlestatus status) throws exception { logger.info("ssionidle"); } @override public void exceptioncaught(iossion ssion, throwable cau) throws exception { logger.error(cau.getmessage(), cau); ssion.clo(true); clientssionlist.remove(ssion); } @override public void messagereceived(iossion ssion, object message) throws exception { logger.info("messagereceived:" + message); for(iossion clientssion : clientssionlist){ clientssion.write(message); } } @override public void messagent(iossion ssion, object message) throws exception { logger.info("messagent:" + message); } }}
client :
package com.tch.test.jms.origin.client; import java.awt.gridlayout;import java.awt.event.actionevent;import java.awt.event.actionlistener;import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.chart.chart; import javax.swing.jbutton;import javax.swing.jframe;import javax.swing.jtextarea;import javax.swing.jtextfield; import org.apache.mina.core.runtimeioexception;import org.apache.mina.core.future.connectfuture;import org.apache.mina.core.rvice.ioconnector;import org.apache.mina.core.rvice.iohandleradapter;import org.apache.mina.core.ssion.idlestatus;import org.apache.mina.core.ssion.iossion;import org.apache.mina.filter.codec.protocolcodecfilter;import org.apache.mina.filter.codec.textline.textlinecodecfactory;import org.apache.mina.filter.logging.loggingfilter;import org.apache.mingrass的复数a.transport.socket.nio.niosocketconnector;import org.slf4j.logger;import org.slf4j.loggerfactory; public class nioclient extends jframe{ private static final logger logger = loggerfactory.getlogger(nioclient.class); private static final long rialversionuid = 1l; private jtextarea area = new jtextarea("content :"); private jtextfield textfield = new jtextfield("textfield:"); private jbutton button = new jbutton("nd"); private string message = null; private myclientiohan有效去痘痘dler handler; private iossion ssion; public static void main(string[] args) throws exception { nioclient client = new nioclient(); client.start(); } private void start() throws ioexception{ tbounds(200, 200, 300, 400); tlayout(new gridlayout(3, 1)); add(area); add(textfield); ioconnector connector = new niosocketconnector(); connector.tconnecttimeoutmillis(10 * 1000); connector.getfilterchain().addlast("logger", new loggingfilter()); connector.getfilterchain().addlast("codec", new protocolcodecfilter(new textlinecodecfactory(chart.forname("utf-8")))); handler = new myclientiohandler(this); connector.thandler(handler); button.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent event) { ndmessage(); } }); add(button); tdefaultclooperation(exit_on_clo); tvisible(true); iossion ssion = null; try { connectfuture future = connector.connect(new inetsocketaddress("localhost", 10000)); future.awaituninterruptibly(); ssion = future.getssion(); } catch (runtimeioexception e) { logger.error(e.getmessage(), e); } ssion.getclofuture().awaituninterruptibly(); connector.dispo(); } private void ndmessage() { try { message = textfield.gettext(); textfield.ttext(""); if(ssion == null || ! ssion.isconnected()){ throw new runtimeexception("ssion is null"); } ssion.write(message); } catch (exception e) { e.printstacktrace(); } } class myclientiohandler extends iohandleradapter{ private nioclient client; public myclientiohandler(nioclient client){ this.client = client; } @override public void ssioncreated(iossion ssion) throws exception { logger.info("ssioncreated"); } @override public void ssionopened(iossion ssion) throws exception { logger.info("ssionopened"); client.ssion = ssion; } @override public void ssionclod(iossion ssion) throws exception { logger.info("ssionclod"); } @override public void ssionidle(iossion ssion, idlestatus status) throws exception { logger.info("ssionidle"); } @override public void exceptioncaught(iossion ssion, throwable cau) throws exception { logger.error(cau.getmessage(), cau); ssion.clo(true); } @override 赤诚善良 public void messagereceived(iossion ssion, object message) throws exception { logger.info("messagereceived: " + message); if (message.tostring().equalsignoreca("bye")) { ssion.clo(true); } area.ttext(area.gettext().trim()+"\n"+message); } @override public void messagent(iossion ssion, object message) throws exception { logger.info("messagent: " + message); } } }
ok.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。
本文发布于:2023-04-03 22:42:56,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/a82ed49c41478577a309a210afeb5ab7.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Java NIO实现聊天功能.doc
本文 PDF 下载地址:Java NIO实现聊天功能.pdf
留言与评论(共有 0 条评论) |