最近写了个Java NIO聊天室聊天的程序,NIO学习起来比较困难的,我的代码能给大家起到一个抛砖引玉的作用!

服务端:

package test.javanio;  

/**
* @author
* @version
* CreateTime:2010-12-1 下午05:12:11
* Description:
*/
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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger; public class MySocketServer implements Runnable { private boolean running; private Selector selector;
String writeMsg;
StringBuffer sb = new StringBuffer();
SelectionKey ssckey; public MySocketServer() { running = true; } public void init() {
try {
selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.socket().bind(new InetSocketAddress(2345));
ssckey = ssc.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("server is starting..." + new Date());
} catch (IOException ex) {
Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,
null, ex);
}
} public static void main(String[] args) {
MySocketServer server = new MySocketServer();
new Thread(server).start(); } public void execute() {
try {
while (running) {
int num = selector.select();
if (num > 0) {
Iterator<SelectionKey> it = selector.selectedKeys()
.iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid())
continue;
if (key.isAcceptable()) {
System.out.println("isAcceptable");
getConn(key);
} else if (key.isReadable()) {
System.out.println("isReadable");
readMsg(key);
} else if (key.isValid() && key.isWritable()) {
if (writeMsg != null) {
System.out.println("isWritable");
writeMsg(key);
} } else
break; } }
Thread.yield();
} } catch (IOException ex) {
Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,
null, ex);
}
} private void getConn(SelectionKey key) throws IOException {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
System.out.println("build connection :"
+ sc.socket().getRemoteSocketAddress());
} private void readMsg(SelectionKey key) throws IOException {
sb.delete(0, sb.length());
SocketChannel sc = (SocketChannel) key.channel();
System.out.print(sc.socket().getRemoteSocketAddress() + " ");
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
int len = 0;
StringBuffer sb = new StringBuffer();
while ((len = sc.read(buffer)) > 0) {
buffer.flip();
sb.append(new String(buffer.array(), 0, len));
}
if (sb.length() > 0)
System.out.println("get from client:" + sb.toString());
if (sb.toString().trim().toLowerCase().equals("quit")) {
sc.write(ByteBuffer.wrap("BYE".getBytes()));
System.out.println("client is closed "
+ sc.socket().getRemoteSocketAddress());
key.cancel();
sc.close();
sc.socket().close(); } else {
String toMsg = sc.socket().getRemoteSocketAddress() + "said:"
+ sb.toString();
System.out.println(toMsg); writeMsg = toMsg; /*
* Iterator<SelectionKey> it=key.selector().keys().iterator();
*
* while(it.hasNext()){ SelectionKey skey=it.next();
* if(skey!=key&&skey!=ssckey){ SocketChannel client=(SocketChannel)
* skey.channel(); client.write(ByteBuffer.wrap(toMsg.getBytes()));
* }
*
* }
*/ /*
*
* key.attach(toMsg);
* key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);
*/
Iterator<SelectionKey> it = key.selector().keys().iterator(); while (it.hasNext()) {
SelectionKey skey = it.next();
if (skey != key && skey != ssckey) {
if (skey.attachment() != null) {
String str = (String) skey.attachment();
skey.attach(str + toMsg);
} else {
skey.attach(toMsg);
}
skey
.interestOps(skey.interestOps()
| SelectionKey.OP_WRITE);
} }
selector.wakeup();// 可有可无 } } public void run() {
init();
execute();
} private void writeMsg(SelectionKey key) throws IOException { System.out.println("++++enter write+++");
SocketChannel sc = (SocketChannel) key.channel();
String str = (String) key.attachment(); sc.write(ByteBuffer.wrap(str.getBytes()));
key.interestOps(SelectionKey.OP_READ);
}
}

客户端:

package test.javanio;  

/**
* @author
* @version
* CreateTime:2010-12-1 下午05:12:46
* Description:
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Currency.*; public class MySocketClient implements Runnable {
Selector selector; boolean running; SocketChannel sc; public MySocketClient() {
running = true; } public void init() {
try {
sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("localhost", 2345)); } catch (IOException ex) {
Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,
null, ex);
}
} public static void main(String[] args) { MySocketClient client = new MySocketClient();
new Thread(client).start();
} public void execute() { int num = 0;
try {
while (!sc.finishConnect()) {
}
} catch (IOException ex) {
Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,
null, ex);
} ReadKeyBoard rkb = new ReadKeyBoard();
new Thread(rkb).start();
while (running) {
try { ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear(); StringBuffer sb = new StringBuffer();
Thread.sleep(500); while ((num = sc.read(buffer)) > 0) {
sb.append(new String(buffer.array(), 0, num));
buffer.clear();
}
if (sb.length() > 0)
System.out.println(sb.toString());
if (sb.toString().toLowerCase().trim().equals("bye")) {
System.out.println("closed...."); sc.close();
sc.socket().close();
rkb.close();
running = false;
}
} catch (InterruptedException ex) {
Logger.getLogger(MySocketClient.class.getName()).log(
Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MySocketClient.class.getName()).log(
Level.SEVERE, null, ex);
}
} } public void run() {
init();
execute();
} class ReadKeyBoard implements Runnable { boolean running2 = true; public ReadKeyBoard() { } public void close() {
running2 = false;
} public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
while (running2) {
try {
System.out.println("enter some commands:");
String str = reader.readLine();
sc.write(ByteBuffer.wrap(str.getBytes())); } catch (IOException ex) {
Logger.getLogger(ReadKeyBoard.class.getName()).log(
Level.SEVERE, null, ex);
}
} } }
}

原文地址:http://gcguchao8888-sina-com.iteye.com/blog/839021

Java NIO 聊天室实例的更多相关文章

  1. Java Socket聊天室编程(二)之利用socket实现单聊聊天室

    这篇文章主要介绍了Java Socket聊天室编程(二)之利用socket实现单聊聊天室的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 在上篇文章Java Socket聊天室编程(一)之 ...

  2. Java Socket聊天室编程(一)之利用socket实现聊天之消息推送

    这篇文章主要介绍了Java Socket聊天室编程(一)之利用socket实现聊天之消息推送的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 网上已经有很多利用socket实现聊天的例子了 ...

  3. Java NIO原理及实例

    Java NIO是在jdk1.4开始使用的,它既可以说成“新I/O”,也可以说成非阻塞式I/O.下面是java NIO的工作原理: 1. 由一个专门的线程来处理所有的 IO 事件,并负责分发. 2. ...

  4. SignalR 聊天室实例详解(服务器端推送版)

    翻译自:http://www.codeproject.com/Articles/562023/Asp-Net-SignalR-Chat-Room  (在这里可以下载到实例的源码) Asp.Net Si ...

  5. Java NIO Socket编程实例

    各I/O模型优缺点 BIO通信模型 BIO主要的问题在于每当有一个新的客户端请求接入时,服务端必须创建一个新的线程处理新接入的客户端链路,一个线程只能处理一个客户端连接 线程池I/O编程 假如所有可用 ...

  6. Java简单聊天室

    实现Java简单的聊天室 所用主要知识:多线程+网络编程 效果如下图 /** * * @author Administrator * * 简单的多人聊天系统——重点:同时性,异步性 * 1.客户端:发 ...

  7. Unity手游之路<三> 基于Unity+Java的聊天室源码

    http://blog.csdn.net/janeky/article/details/17233199 项目介绍 这是一个简单的Unity项目,实现最基本的聊天室群聊功能.登录聊天室后,用户可以输入 ...

  8. Java之聊天室系统设计一

    任务: 先上实现效果图: 登陆界面: index.jsp: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN& ...

  9. java NIO socket 通信实例

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/zhuyijian135757/article/details/37672151 java Nio 通 ...

随机推荐

  1. POJ——1061 青蛙的约会

    青蛙的约会 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 117858   Accepted: 24599 Descript ...

  2. - > 贪心基础入门讲解四——独木舟问题

    n个人,已知每个人体重,独木舟承重固定,每只独木舟最多坐两个人,可以坐一个人或者两个人.显然要求总重量不超过独木舟承重,假设每个人体重也不超过独木舟承重,问最少需要几只独木舟? 分析: 一个显然的策略 ...

  3. 30、Java并发性和多线程-阿姆达尔定律

    以下内容转自http://ifeve.com/amdahls-law/: 阿姆达尔定律可以用来计算处理器平行运算之后效率提升的能力.阿姆达尔定律因Gene Amdal 在1967年提出这个定律而得名. ...

  4. Cisco IOU Web Interface : Web IOU

    https://github.com/dainok http://sns.clnchina.com.cn/space.php?uid=404779&do=blog&id=4298 ht ...

  5. apache2 ubuntu18.04 配置虚拟端口

    修改3个文件/etc/apache2/apache2.conf/etc/apache2/ports.conf/etc/apache2/sites-available/000-default.conf ...

  6. nginx: 添加文件下载目录

    修改nginx.conf,添加如下行: location /file/ {    alias /usr/share/nginx/html/file/;    add_header Content-di ...

  7. velt-0.1.7开发: KernelConfig的问题

    快乐虾 http://blog.csdn.net/lights_joy/(QQ群:Visual EmbedLinux Tools 375515651) 欢迎转载.但请保留作者信息 VELT的全称是Vi ...

  8. Python3基础(八) 模块

    在程序中定义函数可以实现代码重用.但当你的代码逐渐变得庞大时,你可能想要把它分割成几个文件,以便能够更简单地维护.同时,你希望在一个文件中写的代码能够被其他文件所重用,这时我们应该使用模块(modul ...

  9. 【转】在Oracle中查看各个表、表空间占用空间的大小

    查看当前用户每个表占用空间的大小:    select segment_name,sum(bytes)/1024/1024 from user_extents group by segment_nam ...

  10. java中inputstream的使用

    java中的inputstream是一个面向字节的流抽象类,其依据详细应用派生出各种详细的类. 比方FileInputStream就是继承于InputStream,专门用来读取文件流的对象,其详细继承 ...