基于java NIO 的服务端与客户端代码
在对java NIO selector 与 Buffer Channel 有一定的了解之后,我们进行编写java nio 实现的 客户端与服务端例子:
服务端:
public class NIOChatService {
private static Map<String,SocketChannel> userMap =new HashMap<>();
public static void main(String[] args) throws Exception {
//创建selector 对象
Selector selector =Selector.open();
//创建serverSocketChannel
ServerSocketChannel serverSocketChannel =ServerSocketChannel.open();
//设置为非阻塞
serverSocketChannel.configureBlocking(false);
//绑定端口
serverSocketChannel.bind(new InetSocketAddress(9999));
//监听客户端的连接事件,绑定在selector 上
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//死循环
while(true) {
//阻塞监听,监听是否有事件发生
selector.select();
//获取事件发生的selectionkey
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for(SelectionKey key:selectedKeys) {
if(key.isAcceptable()) {
//如果是客户端的连接的话
ServerSocketChannel serverchannel=(ServerSocketChannel)key.channel();
//获取socketchannel 传输对象
SocketChannel accept = serverchannel.accept();
accept.configureBlocking(false);
accept.register(selector, SelectionKey.OP_READ);
//保存连接的用户信息
String keys ="{"+UUID.randomUUID()+"}";
userMap.put(keys, accept);
System.out.println(userMap);
}
else if(key.isReadable()) {
//只要能进入到可读的,那么channel 一定是SocketChannel
SocketChannel socketChannel =(SocketChannel)key.channel();
ByteBuffer bytebuffer =ByteBuffer.allocate(1024);
//读取数据到ByteBuffer
socketChannel.read(bytebuffer);
bytebuffer.flip();
Charset charset =Charset.forName("utf-8");
String receiveMsg=String.valueOf(charset.decode(bytebuffer).array());
for(Map.Entry<String, SocketChannel> entry:userMap.entrySet()) {
ByteBuffer bys1 =ByteBuffer.allocate(1024);
bys1.put((entry.getKey()+receiveMsg).getBytes());
SocketChannel channel =entry.getValue();
bys1.flip();
channel.write(bys1);
}
}
//一定要进行clear 操作
selectedKeys.clear();
}
;
}
}
}
客户端例子:
public class JavaNioClient {
public static void main(String[] args) throws Exception {
//建立Selector
Selector selector =Selector.open();
SocketChannel socketChannel=SocketChannel.open();
//设置非阻塞
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_CONNECT);
socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
while(true) {
selector.select();
Set<SelectionKey> setionkey =selector.selectedKeys();
for(SelectionKey kk :setionkey) {
if(kk.isConnectable()) {
//从selectionkey 获取socketChannel
SocketChannel socket=(SocketChannel)kk.channel();
//手动建立连接
if(socket.isConnectionPending()) {
socket.finishConnect();
//写数据
ByteBuffer byteB = ByteBuffer.allocate(1024);
byteB.put((System.currentTimeMillis()+"连接ok").getBytes());
byteB.flip();
socket.write(byteB);
//jdk1.5 线程池
ExecutorService exe =Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
exe.submit(new Thread() {
@Override
public void run() {
while(true) {
String msg=null;
byteB.clear();
//标准键盘输入
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
try {
msg =br.readLine();
ByteBuffer bytec = ByteBuffer.allocate(1024);
bytec.put(msg.getBytes());
bytec.flip();
socket.write(bytec);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
socket.register(selector, SelectionKey.OP_READ);
}
else if(kk.isReadable()) {
//从selectionkey 获取socketChannel
SocketChannel socket=(SocketChannel)kk.channel();
ByteBuffer by =ByteBuffer.allocate(1024);
int a=socket.read(by);
//if(a>0) {
String receive =new String(by.array());
System.out.println(receive);
//}
}
setionkey.clear();
}
}
}
}
基于java NIO 的服务端与客户端代码的更多相关文章
- Java Se : Java NIO(服务端)与BIO(客户端)通信
Java目前有三种IO相关的API了,下面简单的说一下: BIO,阻塞IO,最常用的Java IO API,提供一般的流的读写功能.相信学习Java的人,都用过. NIO,非阻塞IO,在JDK1.4中 ...
- TCP通信服务端及客户端代码
Java TCP通信使用的是Socket(客服端)和ServerSocket(服务端),具体代码如下. server端代码: import java.io.BufferedReader; import ...
- java socket实现服务端,客户端简单网络通信。Chat
之前写的实现简单网络通信的代码,有一些严重bug.后面详细写. 根据上次的代码,主要增加了用户注册,登录页面,以及实现了实时显示当前在登录状态的人数.并解决一些上次未发现的bug.(主要功能代码参见之 ...
- C++封装的基于WinSock2的TCP服务端、客户端
无聊研究Winsock套接字编程,用原生的C语言接口写出来的代码看着难受,于是自己简单用C++封装一下,把思路过程理清,方便自己后续翻看和新手学习. 只写好了TCP通信服务端,有空把客户端流程也封装一 ...
- socket模块实现基于UDP聊天模拟程序;socketserver模块实现服务端 socket客户端代码示例
socket模块 serSocket.setblocking(False) 设置为非阻塞: #coding=utf-8 from socket import * import time # 用来存储所 ...
- JAVA笔记15__TCP服务端、客户端程序 / ECHO程序 /
/** * TCP:传输控制协议,采用三方握手的方式,保证准确的连接操作. * UDP:数据报协议,发送数据报,例如:手机短信或者是QQ消息. */ /** * TCP服务器端程序 */ public ...
- java环信服务端注册IM代码
下载环信api代码 https://github.com/easemob/emchat-server-examples 里面包含各种语言版本,我只下载了java版emchat-server-java ...
- java TCP 通信:服务端与客服端
1.首先先来看下基于TCP协议Socket服务端和客户端的通信模型: Socket通信步骤:(简单分为4步) 1.建立服务端ServerSocket和客户端Socket 2.打开连接到Socket的输 ...
- gSOAP calc服务端与客户端示例
1. Web服务定义描述头文件 typedef double xsd__double; int ns__add(xsd__double a, xsd__double b, xsd__double &a ...
随机推荐
- Django下的templates 和 static静态文件
如果Django顶层目录中没有templates的话,就自己新建一个Directory ,这个文件是存放html文件的 1)如果在views里面用render(request,"" ...
- js 购物车的实现
购物车原理:创建一个构造函数,把涉及到的项目写成方法,然后把这些方法放到构造函数的原型对象上,通过按钮绑定,调用原型对象上的方法,实现对涉及项目的改变 html代码: <!DOCTYPE htm ...
- Tomcat 7集群基于redis的session共享设置
经过测试之后,发现是tomcat中redis相关jar包问题,替换jar包后A产品运行正常. tomcat/lib目录下将commons-pool2-2.1.jar.jedis-2.1.0.jar.t ...
- 一个rcu回调导致的简单死锁
在自有模块的处理中,我们设计了一个内核线程去做gc, 但同时,我们又用到了rcu,rcu中也会去抢gc的锁,由于该锁用的spin_lock,而不是spin_lock_bh,并没有关软中断,所以在rcu ...
- TypeScript语言学习笔记(2)
接口 // 在参数类型中定义约束 function printLabel(labelledObj: { label: string }) { console.log(labelledObj.label ...
- Haskell语言学习笔记(70)NonEmpty
NonEmpty(非空列表) infixr 5 :| data NonEmpty a = a :| [a] deriving (Eq, Ord) instance Functor NonEmpty w ...
- PHP查询登录中的sql注入
---------------------------------------------------------------------------------------------------- ...
- Git设置/取消代理
设置代理 git config --global http.proxy http://proxy.com:1234 git config --global https.proxy http://pro ...
- 译:SQL Server的Missing index DMV的 bug可能会使你失去理智---慎重看待缺失索引DMV中的信息
注: 本文译自https://www.sqlskills.com/blogs/paul/missing-index-dmvs-bug-that-could-cost-your-sanity/ 原文作者 ...
- 多线程 死锁 wait(int i) notifyAll()
public class ThreadDemo5 { public static void main(String[] args){ Pool pool = new Pool(); Productor ...