Java Nio Socket通讯
Server端:
#############服务器端连接请求处理###############
public class MultiplexerServer implements Runnable { /**多路复用器,SocketChannel注册到Selector.Selector轮询监听Channel网络事件*/
private Selector selector; private ServerSocketChannel serverSocketChannel; private boolean stop; public MultiplexerServer(int port) {
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("[" + getClass().getSimpleName() + "] start in port [" + port + "]");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
} @Override
public void run() {
while (!stop) {
try {
selector.select(1000);
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
iterator.remove();
try {
/**处理请求连接*/
handle(selectionKey);
} catch (Exception e) {
if (selectionKey != null) {
selectionKey.cancel();
if (selectionKey.channel() != null) {
selectionKey.channel().close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} }
try {
/**Selector关闭后,注册的Channel及Pipe等资源都会自动关闭(不需要重复关闭资源)*/
if (selector != null) {
selector.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} public void stop(boolean stop) {
this.stop = stop;
} private void handle(SelectionKey key) throws IOException {
if (key.isValid()) {
if (key.isAcceptable()) { // 新连接
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
}
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(buffer);
if (readBytes > 0) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println(new String(bytes, "UTF-8"));
/**响应客户端请求*/
response(sc, new Respone("server received", 0));
} else if (readBytes == 0) {
;
} else { // 客户端关闭连接
key.cancel();
sc.close();
}
}
}
} private void response(SocketChannel sc, Respone respone) throws IOException{
if (respone != null && sc != null && sc.isConnected()) {
String json = respone.toString();
byte[] bytes = json.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
buffer.flip();
sc.write(buffer);
}
}
} ###############服务器端响应################
public class Respone { private String data; private int status; public Respone() { } public Respone(String data, int status) {
this.data = data;
this.status = status;
} public String getData() {
return data;
} public void setData(String data) {
this.data = data;
} public int getStatus() {
return status;
} public void setStatus(int status) {
this.status = status;
} @Override
public String toString() {
return "{\"data\":" + data + ",\"status\":" + status + "}";
}
} #############服务端入口##############
public class NioServer { public static void start(int port) {
Executors.newSingleThreadExecutor().submit(new MultiplexerServer(port));
} public static void main(String []args) {
int port = 8181;
if (args != null && args.length == 1) {
port = Integer.parseInt(args[0]);
}
NioServer.start(port);
}
}
Client段:
public class NioClientConnection implements Runnable { private String host; private int port; private Selector selector; private SocketChannel socketChannel; private boolean stop; public NioClientConnection(String host, int port) {
this.host = host;
this.port = port;
try {
selector = Selector.open();
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
} @Override
public void run() {
try {
connect();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
while (!stop) {
try {
selector.select(1000);
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
try {
// 响应服务
doResponse(selectionKey);
} catch (Exception e) {
e.printStackTrace();
if (selectionKey != null) {
selectionKey.cancel();
if (selectionKey.channel() != null) {
selectionKey.channel().close();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
if (selector != null) {
selector.close();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
} private void connect() throws IOException {
if (socketChannel.connect(new InetSocketAddress(host, port))) {
socketChannel.register(selector, SelectionKey.OP_READ);
send(socketChannel);
} else {
socketChannel.register(selector, SelectionKey.OP_CONNECT);
}
} private void send(SocketChannel sc) throws IOException {
byte[] bytes = "Hello, Server".getBytes();
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
buffer.flip();
sc.write(buffer);
if (!buffer.hasRemaining()) {
System.out.println("send msg sucess");
}
} private void doResponse(SelectionKey key) throws IOException{
if (key.isValid()) {
SocketChannel sc = (SocketChannel) key.channel();
if (key.isConnectable()) {
if (sc.finishConnect()) {
sc.register(selector, SelectionKey.OP_READ);
send(socketChannel);
}
}
if (key.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(buffer);
if (readBytes > 0) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println(new String(bytes, "UTF-8"));
/**关闭连接*/
stop = true;
} else if (readBytes == 0) {
;
} else { // 客户端关闭连接
key.cancel();
sc.close();
}
}
}
} } public class NioClient { public static void start(String host, int port) {
Executors.newSingleThreadExecutor().execute(new NioClientConnection(host, port));
} public static void main(String []args) {
String host = "127.0.0.1";
int port = 8181;
if (args != null && args.length == 2) {
host = args[0];
port = Integer.valueOf(args[1]);
}
NioClient.start(host, port);
} }
Java Nio Socket通讯的更多相关文章
- Java nio socket与as3 socket(粘包解码)连接的应用实例
对Java nio socket与as3 socket连接的简单应用 <ignore_js_op>Java nio socket与as3 socket连接的应用实例.rar (9.61 K ...
- 【Java TCP/IP Socket】Java NIO Socket VS 标准IO Socket
简介 Java NIO从JDK1.4引入,它提供了与标准IO完全不同的工作方式. NIO包(java.nio.*)引入了四个关键的抽象数据类型,它们共同解决传统的I/O类中的一些问题. 1. ...
- JAVA NIO Socket通道
DatagramChannel和SocketChannel都实现定义读写功能,ServerSocketChannel不实现,只负责监听传入的连接,并建立新的SocketChannel,本身不传输数 ...
- Java NIO Socket 非阻塞通信
相对于非阻塞通信的复杂性,通常客户端并不需要使用非阻塞通信以提高性能,故这里只有服务端使用非阻塞通信方式实现 客户端: package com.test.client; import java.io. ...
- Java NIO Socket编程实例
各I/O模型优缺点 BIO通信模型 BIO主要的问题在于每当有一个新的客户端请求接入时,服务端必须创建一个新的线程处理新接入的客户端链路,一个线程只能处理一个客户端连接 线程池I/O编程 假如所有可用 ...
- java NIO socket 通信实例
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/zhuyijian135757/article/details/37672151 java Nio 通 ...
- java nio socket使用示例
这个示例,实现一个简单的C/S,客户端向服务器端发送消息,服务器将收到的消息打印到控制台,并将该消息返回给客户端,客户端再打印到控制台.现实的应用中需要定义发送数据使用的协议,以帮助服务器解析消息.本 ...
- erlang和java的socket通讯----最简单,初次实现。
直接上源码,留做纪念. 有点简单,大家不要笑,初次实现. 功能描述:java发送数据给erlang,erlang将收到的数据重复两次再发送给java. erlang源码:模块tcp_listen -m ...
- Java C++ Socket通讯
import java.net.*; import javax.swing.plaf.SliderUI; /** * 与c语言通信(java做client,c/c++做server,传送一个结构) * ...
随机推荐
- 查找文件which locate find
(1)which:查找命令文件路径 which ls //命令的路径查找是根据PATH环境变量 whereis ls echo $PATH //打印PATH环境变量 (2)locate:查找任意文件 ...
- python的Django使用mysql基本操作
环境:Centos6.6 ,python2.6 准备工作: mysql的安装,以及MySQL-python的安装 http://www.cnblogs.com/zychengzhiit1/p/4437 ...
- Centos的 mysql for python的下载与安装
mysql-python的安装包下载地址:http://sourceforge.net/projects/mysql-python/files/latest/download linux环境是 Cen ...
- 洛谷P1850换教室
题目传送门 理解题意:给定你一个学期的课程和教室数量以及教室之间的距离还有换教室成功的概率,求一个学期走的距离的期望最小值 题目是有够恶心的,属于那种一看就让人不想刷的题目...很明显的动规,但是那个 ...
- Compass用法
一.什么是Compass? Compass是Sass的工具库,Compass在SASS的基础上,封装了一系列有用的模块去补充Sass的功能,类似Javascript和jQuery 二.安装 之前已经写 ...
- RMQ入门
注:为方便描述算法 便于记忆 所以ST的代码用Pascal书写 见谅 RMQ,即Range Minimum/Maximum Query问题,给定一个区间,询问不同子区间的最值问题. 当询问次数较少时, ...
- CodeForces - 995B Suit and Tie
题面在这里! 明明可以出成n<=1e5但是因为拒绝写数据结构而只出到n<=100,,,出题人真的很棒棒.. 一个显然的贪心就是,把和当前序列最左端的数匹配的数移到它的右边,这样迭代下去总是 ...
- 【Floyd】噪音恐惧症
[UVA10048]噪音恐惧症 题面略 试题分析:直接Floyd一下维护u到v的路径最大值最小就可以了,1A 代码: #include<iostream> #include<cstr ...
- JDK源码学习笔记——LinkedList
一.类定义 public class LinkedList<E> extends AbstractSequentialList<E> implements List<E& ...
- java浏览器控件jxbrowser(简单demo模拟自动登录与点击)
写在前面: 老大让我写个脚本自动给他写dms有一段时间了,说实话当时不知道老大指的这个脚本是什么?毕竟是做web的,难道是写个数据库sql语句脚本吗?也就放在了一边.巧了,最近一个朋友说他之前写了个程 ...