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,传送一个结构) * ...
随机推荐
- TCP握手协议简述
TCP握手协议简述在TCP/IP协议中,TCP协议提供可靠的连接服务,采用三次握手建立一个连接.第一次握手:建立连接时,客户端发送syn包(syn=j)到服务器,并进入SYN_SEND状态,等待服务器 ...
- 2018 ACM-ICPC 北京网络赛
Problem A 最短路,跑一下dij就可以了. Problem B Problem C 按照题意模拟,不过坑点很多 1.注意字典序: 2.注意挑战的时候失败的那个人要把当前所有桌子上的牌都拿走 P ...
- Linux基础系列-Day1
Linux发展简史 Unix:1969年由美国电话电报公司(AT&T)贝尔实验室的两个工程师所创造的操作系统,它允许计算机同时处理多用户和程序. BSD:重要的Unix分支,1977年由加州大 ...
- CSS 笔记——背景布局
4. 背景布局 -> 背景 (1)background 基本语法 background : background-color || background-image || background- ...
- POJ1704 Georgia and Bob 博弈论 尼姆博弈 阶梯博弈
http://poj.org/problem?id=1704 我并不知道阶梯博弈是什么玩意儿,但是这道题的所有题解博客都写了这个标签,所以我也写了,百度了一下,大概是一种和这道题类似的能转换为尼姆博弈 ...
- 【树形dp】Godfather
[POJ3107]Godfather Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 7212 Accepted: 253 ...
- 【状态压缩DP】NOIP2005-river过河
[问题描述] 在河上有一座独木桥,一只青蛙想沿着独木桥从河的一侧跳到另一侧.在桥上有一些石子,青蛙很讨厌踩在这些石子上.由于桥的长度和青蛙一次跳过的距离都是正整数,我们可以把独木桥上青蛙可能到达的点看 ...
- [NOIp2016提高组]组合数问题
题目大意: 给定n,m和k,对于所有的0<=i<=n,0<=j<=min(i,m)有多少对(i,j)满足C(j,i)是k的倍数. 思路: 先预处理出组合数,再预处理一下能整除个 ...
- Java并发(六):volatile的实现原理
synchronized是一个重量级的锁,volatile通常被比喻成轻量级的synchronized volatile是一个变量修饰符,只能用来修饰变量. volatile写:当写一个volatil ...
- linux svn 配置
#svnadmin create projectname #vi projectname/conf/svnserve.conf anon-access = noneauth-access =write ...