Java 异步通信 程序
来源:互联网 发布:php mysql 开启预编译 编辑:程序博客网 时间:2024/06/05 10:06
Java异步通信
客户端:package cn.xiao;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;import java.nio.ByteBuffer;import java.nio.CharBuffer;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;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder;import java.util.Iterator;public class TCPServer {protected Selector selector;protected Charset charset = Charset.forName("UTF-8");protected CharsetEncoder charsetEncoder = charset.newEncoder();protected CharsetDecoder charsetDecoder = charset.newDecoder();int count = 1;/** * @throws Exception */public TCPServer() throws Exception{this(8888);}/** * @param port * @throws Exception */public TCPServer(int port) throws Exception {selector = Selector.open();ServerSocketChannel ssc = ServerSocketChannel.open();ssc.socket().bind(new InetSocketAddress(port)); // portssc.configureBlocking(false);ssc.register(selector, SelectionKey.OP_ACCEPT);// registerwhile (true) {// selector 线程。select() 会阻塞,直到有客户端连接,或者有消息读入selector.select();Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();while (iterator.hasNext()) {SelectionKey selectionKey = iterator.next();iterator.remove(); // 删除此消息// 并在当前线程内处理handleSelectionKey(selectionKey);}}}/** * @param selectionKey * @throws Exception */public void handleSelectionKey(SelectionKey selectionKey) throws Exception {if (selectionKey.isAcceptable()) {ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();SocketChannel socketChannel = ssc.accept();socketChannel.configureBlocking(false);Socket socket = socketChannel.socket();// 立即注册一个 OP_READ 的SelectionKey, 接收客户端的消息SelectionKey key = socketChannel.register(selector,SelectionKey.OP_READ);SocketAddress clientInfo = socket.getRemoteSocketAddress();key.attach("第 " + (count++) + " 个客户端 [" + clientInfo + "]");// 打印println(key.attachment() + " 连接成功");} else if (selectionKey.isReadable()) {// 有消息进来ByteBuffer byteBuffer = ByteBuffer.allocate(100);SocketChannel sc = (SocketChannel) selectionKey.channel();try {int len = sc.read(byteBuffer);// 如果len>0,表示有输入。如果len==0, 表示输入结束。需要关闭 socketChannelif (len > 0) {byteBuffer.flip();String msg = charsetDecoder.decode(byteBuffer).toString();println(selectionKey.attachment() + " :" + msg);// 根据客户端的消息,查找到对应的输出String newMsg = "****************";ByteBuffer bt = charsetEncoder.encode(CharBuffer.wrap(newMsg + "\n"));sc.write(bt);} else {// 输入结束,关闭 socketChannelprintln(selectionKey.attachment()+ " 已关闭连接");sc.close();}} catch (Exception e) {// 如果read抛出异常,表示连接异常中断,需要关闭 socketChannele.printStackTrace();sc.close();}} else if (selectionKey.isWritable()) {println("TODO: isWritable()");} else if (selectionKey.isConnectable()) {println("TODO: isConnectable()");} else {println("TODO: else");}}/** * @param object */public static void println(Object object) {System.out.println(object);}/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {new TCPServer();}}
我是业余的,复制,粘贴代码就可运行,原理要自己领悟哈!package cn.xiao;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.Socket;import java.io.InputStream;public class TCPClient extends Thread {public void run() {try {Socket socket = new Socket("127.0.0.1", 8888);OutputStream ous = socket.getOutputStream();InputStream ins = socket.getInputStream();BufferedReader r = new BufferedReader(new InputStreamReader(ins, "UTF-8"));// 发送服务器ous.write(">>>>>>>>>>>>>>>>".getBytes("UTF-8"));ous.flush();// 接收给服务器System.out.println(">>>> " + r.readLine());// 发送服务器ous.write("<<<<<<<<<<<<<<<<".getBytes("UTF-8"));ous.flush();// 接收服务器System.out.println(">>>> " + r.readLine());Thread.sleep(3*1000);ins.close();ous.close();socket.close();} catch (Exception e) {e.printStackTrace();}}/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {for (int i = 0; i < 3; i++) {try {new TCPClient().start();} catch (Exception e) {e.printStackTrace();}}}}
- Java 异步通信 程序
- Java异步通信
- Java AIO-异步通信
- Java AIO-异步通信
- nio socket 异步通信 java
- linux c 异步通信 聊天程序
- java&&socket&&通信程序
- Java NIO(异步IO)Socket通信例子
- Java Aio Socket异步通信例子
- java-非阻塞异步通信-NIO初探
- 异步通信
- 异步通信
- 基于异步通信层的注册小程序
- 写的异步通信CAsyncSocket程序m_hsoceket总是非法,请教!
- linux网络编程:用C语言实现的聊天程序(同步通信)、(异步通信)
- 使用Java NIO实现异步的socket通信
- java server 多client异步socket通信demo
- 同步通信 异步通信 概念
- linux下手动安装apache详解
- 014 win10是使用优化两则
- Codeforce 621(A,B,C,D,E)
- Android初学习 - implements OnClickListener
- 南阳OJ 28:大数阶乘
- Java 异步通信 程序
- 详解赋范空间——图像处理中的数学原理详解24
- 面试笔试杂项积累-leetcode 61-65
- 理解RESTful架构
- 安卓进阶之自定义View
- Android 调整图标和字体大小
- jQuery性能提升方法
- androidStudio导入SlidingMenu第三方框架中出现的问题
- 第13讲-数值型数据的存储-练习