170407、java基于nio工作方式的socket通信
客户端代码:
/**
*
*/
package com.bobohe.nio; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset; /**
* 实现TCP/IP+NIO 方式的系统间通讯的代码,客户端:
*
* @author solo
*/
public class NioClient { /**
* create solo
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String host = "127.0.0.1";
int port = 9527; Selector selector = Selector.open(); SocketChannel clientChannel = SocketChannel.open();
clientChannel.configureBlocking(false);
clientChannel.connect(new InetSocketAddress(host, port)); clientChannel.register(selector, SelectionKey.OP_CONNECT); BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
while (true) {
if (clientChannel.isConnected()) {
String command = systemIn.readLine();
clientChannel.write(Charset.forName("UTF-8").encode(command)); if (command == null || "quit".equalsIgnoreCase(command)) {
System.out.println("Client quit!"); systemIn.close();
clientChannel.close();
selector.close();
System.exit(0);
} } //最长阻塞10s
int nKeys = selector.select(10 * 1000);
if (nKeys > 0) {
for (SelectionKey selectionKey : selector.selectedKeys()) {
if (selectionKey.isConnectable()) {
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
socketChannel.finishConnect();
} else if (selectionKey.isReadable()) {
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
StringBuilder sb = new StringBuilder(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
try {
int readBytes = 0;
int ret = 0;
while ((ret = socketChannel.read(byteBuffer)) > 0) {
readBytes += ret;
byteBuffer.flip(); sb.append(Charset.forName("UTF-8").decode(byteBuffer).toString()); byteBuffer.clear();
} if (readBytes == 0) {
/*
* handle Exception
*/
System.err.println("handle opposite close Exception");
socketChannel.close();
}
} catch (IOException e) {
/*
* handle Exception
*/
System.err.println("handle read Exception");
socketChannel.close();
} finally {
byteBuffer.clear();
} String message = sb.toString();
System.out.println(message);
}
}
selector.selectedKeys().clear(); } else {
/*
* handle Exception
* 三秒没有响应则打印错误信息
*/
System.err.println("handle select timeout Exception");
clientChannel.close();
} }
} }
服务端代码:
/**
*
*/ package com.bobohe.nio; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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.nio.charset.Charset; /**
* 实现TCP/IP+NIO 方式的系统间通讯的代码,服务器端: SocketChannel和ServerSocketChannel两个关键的类,网络IO
* 的操作则改为通过ByteBuffer来实现。
*
* @author solo
*/
public class NioServer { /**
* create by solo
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int port = 9527;
System.out.println("Server listen on port: " + port); Selector selector = Selector.open(); ServerSocketChannel serverChannel = ServerSocketChannel.open();
ServerSocket serverSocket = serverChannel.socket();
serverSocket.bind(new InetSocketAddress(port));
serverChannel.configureBlocking(false); serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int nKeys = selector.select();
if (nKeys > 0) {
for (SelectionKey selectionKey : selector.selectedKeys()) {
if (selectionKey.isAcceptable()) {
ServerSocketChannel tempServerChannel = (ServerSocketChannel) selectionKey
.channel();
SocketChannel socketChannel = tempServerChannel
.accept();
if (socketChannel == null) {
continue;
} socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
// try { Thread.sleep(5000); } catch
// (InterruptedException e) { e.printStackTrace(); }
SocketChannel socketChannel = (SocketChannel) selectionKey
.channel(); StringBuilder sb = new StringBuilder();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
try {
int readBytes = 0;
int ret = 0;
while ((ret = socketChannel.read(byteBuffer)) > 0) {
readBytes += ret;
byteBuffer.flip(); sb.append(Charset.forName("UTF-8")
.decode(byteBuffer).toString()); byteBuffer.clear();
} if (readBytes == 0) {
/*
* handle Exception
*/
System.err
.println("handle opposite close Exception");
socketChannel.close();
} String message = sb.toString();
System.out.println("client: "
+ message);
if ("quit".equalsIgnoreCase(message.toString()
.trim())) {
System.out.println("Client has been quit!"); socketChannel.close();
} else if ("serverquit".equalsIgnoreCase(message
.trim())) {
System.out.println("Server has been shutdown!"); socketChannel.close();
serverChannel.close();
selector.close();
System.exit(0);
} else {
socketChannel.write(Charset.forName("UTF-8").encode("Server Handler Done!"));
}
} catch (IOException e) {
/*
* handle Exception
*/
System.err.println("handle read Exception");
socketChannel.close();
} finally {
byteBuffer.clear();
} }
}
selector.selectedKeys().clear(); }
}
} }
170407、java基于nio工作方式的socket通信的更多相关文章
- JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信
阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...
- java体系结构与工作方式 《深入分析java web 技术内幕》第七章
java体系结构与工作方式 7.1 JVM体系结构 何谓JVM JVM(Java Virtual Machine) 通过模拟一个计算机来达到一个计算机所具有的计算功能 指令集:计算机所能识别的机器语言 ...
- 基于Tcp协议的简单Socket通信实例(JAVA)
好久没写博客了,前段时间忙于做项目,耽误了些时间,今天开始继续写起~ 今天来讲下关于Socket通信的简单应用,关于什么是Socket以及一些网络编程的基础,这里就不提了,只记录最简单易懂实用的东西. ...
- 多线程方式实现Socket通信
一.首先,介绍下两类传输协议:TCP:UDP TCP是Tranfer Control Protocol的 简称,是一种面向连接的保证可靠传输的协议.通过TCP协议传输,得到的是一个顺序的无差错的数据流 ...
- 坦克大战--Java类型 ---- (3)实现socket通信
一.实现思路 使用socket通信的一些方法来实现socket通信,客户端和服务端两边需要约定好通信的接口Port(尽量选高的),客户端需要服务端的IP地址,以实现数据交流. 同时,客户端和服务端需要 ...
- java之接口开发-初级篇-socket通信
socket通信实现util包类实现 public class SocketThread extends Thread { public void run() { while (true) { // ...
- java学习小笔记(三.socket通信)【转】
三,socket通信1.http://blog.csdn.net/kongxx/article/details/7288896这个人写的关于socket通信不错,循序渐进式的讲解,用代码示例说明,运用 ...
- 基于TCP和UDP的Socket通信
TCP的Socket通信 TCP是面向连接的,安全的协议,它是一对一的关系 server client 上面只是单个客户端同服务器通信,可使用多线程编程实现多个客户端的通信 UDP的Socket通信 ...
- java nio实现非阻塞Socket通信实例
服务器 package com.java.xiong.Net17; import java.io.IOException; import java.net.InetSocketAddress; imp ...
随机推荐
- uploadify onSelect
uploadify onSelect [return false]停止选择 $("#fileEleId").uploadify({ 'width': _option.width, ...
- Java类载入器(一)——类载入器层次与模型
类载入器 虚拟机设计团队把类载入阶段中的"通过一个类的全限定名来获取描写叙述此类的二进制字节流"这个动作放到Java虚拟机外部去实现.以便让应用程序自己决定怎样去获取所须要的类 ...
- pcie dma的玩法
There is some issue with the implement script. So I took the manual steps. 1. Created the pcie core ...
- 李洪强iOS经典面试题37-解释垃圾回收的原理
李洪强iOS经典面试题37-解释垃圾回收的原理 问题 我们知道,Android 手机通常使用 Java 来开发,而 Java 是使用垃圾回收这种内存管理方式. 那么,ARC 和垃圾回收对比,有什么 ...
- js基本知识1
Javascript 作用 1. 网页特效 2. 用户交互 3. 表单验证 Js 就是可以用来控制 结构 和 样式 . 1.2 体验js 认识常用的三个输出语句. 都属于 js 内置对象 . 大家买手 ...
- (转载)C++STL中vector容器的用法
vector是C++标准模板库中的部分内容,它是一个多功能的,能够操作多种数据结构和算法的模板类和函数库.vector之所以被认为是一个容器,是因为它能够像容器一样存放各种类型的对象,简单地说vec ...
- ES-PHP向ES批量添加文档报No alive nodes found in your cluster
ES-PHP向ES批量添加文档报No alive nodes found in your cluster 2016年12月14日 12:31:40 阅读数:2668 参考文章phpcurl 请求Chu ...
- 微信小程序 - WapRequest.js
文件位于 utils/WapRequest.js 封装了所有接口请求和wap站点的controller请求,代码示例 /** * 选择 洲 国家 * 无参数 */ WapRequest.prototy ...
- golang Time to String
golang Time to String allenhaozi · 2016-09-02 09:00:00 · 2447 次点击 · 预计阅读时间 1 分钟 · 19分钟之前 开始浏览 这是一个创建 ...
- 二分图匹配 + 最小点覆盖 - Vertex Cover
Vertex Cover Problem's Link Mean: 给你一个无向图,让你给图中的结点染色,使得:每条边的两个顶点至少有一个顶点被染色.求最少的染色顶点数. analyse: 裸的最小点 ...