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 ...
随机推荐
- unity, imageEffect在android上不显示的问题
使用imageEffect做了个景深特效,原理很简单,就是一张清晰大图和一张模糊小图根据z值进行混合,z值小的像素清晰大图的比例高一些,z值大的像素模糊小图的比例高一些. 在pc上是ok的,但打出an ...
- CentOS 7 下挂载NTFS文件系统并实行开机自动挂载
CentOS 7 下想要挂载NTFS的文件系统该怎么办呢? 我们需要一个NTFS-3G工具,并编译它之后在mount就可以了,就这么简单. 首先要进入官网下载NTFS-3G工具 http://www. ...
- 博客已迁移至512z.com
本博客已迁移至http://blog.512z.com,此处今后不再更新
- C# 文件与二进制互转数据库写入读出
//这个方法是浏览文件对象 private void button1_Click(object sender, EventArgs e) { //用户打开文件浏览 using (OpenFileDia ...
- C++ virtual继承
C++ virtual继承的还有一种名称是菱形继承.主要目的是用于解决从不同类继承来的同名数据成员在内存中有不同的拷贝.造成数据不统一的问题,以致于在进行类释放时造成内存泄漏. 将共同的基类作为虚基类 ...
- Eclipse上Hadoop插件中Run On Hadoop原理[转]
通过Eclipse的hadoop插件中的"run on hadoop"命令的原理:它不是把jar包发送到hadoop集群上去运行,而只是使用了hadoop集群上的hdfs,从hdf ...
- SQL Server 2008 允许远程链接 解决方法
用户在使用SQL Server 2008远程链接时,可能会弹出如下对话框: 在链接SQL服务器时发生网络链接错误或特定实例错误.SQL服务器不存在或者链接不成功.请验证用户名是否正确或SQL服务器是否 ...
- 【转】shell pipe与输入输出重定向的区别
http://www.cnblogs.com/chengmo/archive/2010/10/21/1856577.html
- CodeForces 1A Theatre Square
A - Theatre Square Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u ...
- am335x 内核频率 ddr3频率 电压调整
由Makefile可知,SPL的入口在u-boot-2011.09-psp04.06.00.08\arch\arm\cpu\armv7\start.S中 SPL的功能无非是设置MPU的Clock.PL ...