基于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 ...
随机推荐
- UIPanGestureRecognizer translateInView, locationInView
假设在panGesture的回调事件里已经拿到了panGestureRecognizer CGPoint point = [panGestureRecognizer locationInView:se ...
- 尚硅谷redis学习3-redis启动以后的杂项
redis速度很快,运行benchmark可以看出,各项运行速度可达100000次每秒 redis默认有16个数据库,分别是0, 1 ... 15,默认在0号库,可以通过select num转到其它库 ...
- sql server 2008 数据库可疑的解决步骤
备份并新建同名数据库,并替换原数据文件 1 把问题数据库备份后直接删除 停掉SQLSERVER服务,把服务器上出问题的数据库, 假设名称为 test的数据库文件及日志文件备份到其他目录,然后直接将其删 ...
- Emac
https://emacs-china.org/ 启动 console模式的emacs,$emacs -nw 学习参考: 1)<21天精通emacs> 2)Emacs常用命令简集. 3)& ...
- linux 3.10 tcp的accept测试
net.ipv4.tcp_abort_on_overflow 为 0 有个兄弟跟我说accept的时候,如果故意不去accept,那么客户端connect的时候,一开始很快,后来就很慢: connec ...
- ARP欺骗与MITM(中间人攻击)实例
ARP协议(address resolution protocol):地址解析协议 一台主机和另一台主机通信,要知道目标的IP地址,但是在局域网中传输数据的网卡却不能直接识别IP地址,所以用ARP解析 ...
- APP安全性测试总结--网上转载
移动APP安全测试 老鹰a0人评论7103人阅读2018-08-06 16:22:07 1 移动APP安全风险分析 1.1 安全威胁分析 安全威胁从三个不同环节进行划分, ...
- 自行编译mwan加入openwrt里
参考源文:http://www.right.com.cn/forum/thread-124449-1-1.html 本例以 opoenwrt 12.09正式版为例,原软件来自openwrt 英文论坛: ...
- Mac下如何安装WebStorm + 破解
1.官网下载 下载地址 选择好系统版本以后,点击DOWNLOAD 2.安装 双击下载好的安装包.将WebStromt拖入application文件夹,然后在Launchp ...
- 修改Http消息的消息头Host
在 HttpURLConnection 类中直接使用如下代码无法修改Host的值: connection.setRequestProperty("Host", host); 需要在 ...