当前位置:网站首页>NiO example
NiO example
2022-07-27 08:42:00 【Mangxiao】

Server side
package com.mang.NIO.nsync;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
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.util.Iterator;
import java.util.Set;
public class EchoServer {
private Selector selector = null;
private ServerSocketChannel serverSocketChannel = null;
private int port = 8000;
private Charset charset = Charset.forName("GBK");
public EchoServer() throws IOException {
this.selector = Selector.open();
this.serverSocketChannel = ServerSocketChannel.open();
this.serverSocketChannel.socket().setReuseAddress(true);
this.serverSocketChannel.configureBlocking(false);
this.serverSocketChannel.socket().bind(new InetSocketAddress(this.port));
System.out.println(" Server startup ");
}
public void service() throws IOException {
this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
while(this.selector.select() > 0) {
Set readyKeys = this.selector.selectedKeys();
Iterator it = readyKeys.iterator();
while(it.hasNext()) {
SelectionKey key = null;
try {
key = (SelectionKey)it.next();
it.remove();
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
SocketChannel socketChannel = ssc.accept();
PrintStream var10000 = System.out;
InetAddress var10001 = socketChannel.socket().getInetAddress();
var10000.println(" Customer connection received , come from :" + var10001 + ":" + socketChannel.socket().getPort());
socketChannel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.register(this.selector, 5, buffer);
}
if (key.isReadable()) {
this.receive(key);
}
if (key.isWritable()) {
this.send(key);
}
} catch (IOException var8) {
var8.printStackTrace();
try {
if (key != null) {
key.cancel();
key.channel().close();
}
} catch (Exception var7) {
var8.printStackTrace();
}
}
}
}
}
public void send(SelectionKey key) throws IOException {
ByteBuffer buffer = (ByteBuffer)key.attachment();
SocketChannel socketChannel = (SocketChannel)key.channel();
buffer.flip();
String data = this.decode(buffer);
if (data.indexOf("\r\n") != -1) {
String outputData = data.substring(0, data.indexOf("\n") + 1);
System.out.print(outputData);
ByteBuffer outputBuffer = this.encode("echo:" + outputData);
while(outputBuffer.hasRemaining()) {
socketChannel.write(outputBuffer);
}
ByteBuffer temp = this.encode(outputData);
buffer.position(temp.limit());
buffer.compact();
if (outputData.equals("bye\r\n")) {
key.cancel();
socketChannel.close();
System.out.println(" Close the connection with the customer ");
}
}
}
public void receive(SelectionKey key) throws IOException {
ByteBuffer buffer = (ByteBuffer)key.attachment();
SocketChannel socketChannel = (SocketChannel)key.channel();
ByteBuffer readBuff = ByteBuffer.allocate(32);
socketChannel.read(readBuff);
readBuff.flip();
buffer.limit(buffer.capacity());
buffer.put(readBuff);
}
public String decode(ByteBuffer buffer) {
CharBuffer charBuffer = this.charset.decode(buffer);
return charBuffer.toString();
}
public ByteBuffer encode(String str) {
return this.charset.encode(str);
}
public static void main(String[] args) throws Exception {
EchoServer server = new EchoServer();
server.service();
}
}
client
package com.mang.NIO.nsync;
import jdk.internal.util.xml.impl.Input;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;
public class EchoClient {
private SocketChannel socketChannel = null;
public EchoClient() throws IOException {
socketChannel = SocketChannel.open();
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia,8000);
socketChannel.connect(isa);
System.out.println(" The connection with the server is established successfully ");
}
public static void main(String[] args) throws IOException {
new EchoClient().talk();
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public void talk() {
try {
BufferedReader br = getReader(socketChannel.socket());
PrintWriter pw = getWriter(socketChannel.socket());
BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
while((msg=localReader.readLine())!=null){
pw.println(msg);
System.out.println(br.readLine());
if(msg.equals("bye")) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
边栏推荐
- 接口测试工具-Jmeter压力测试使用
- Transaction, order system add transaction
- Flask request data acquisition and response
- How to uninstall -- Qianxin secure terminal management system
- Creation and simple application of QPushButton button button
- 4275. Dijkstra sequence
- Installation and use of Supervisor
- MCDF top level verification scheme
- JS basic knowledge - daily learning summary ①
- 百人参与,openGauss开源社区这群人都在讨论什么?
猜你喜欢

User management - restrictions

Eval and assert execute one sentence Trojan horse

The shelf life you filled in has been less than 10 days until now, and it is not allowed to publish. If the actual shelf life is more than 10 days, please truthfully fill in the production date and pu

NIO总结文——一篇读懂NIO整个流程

“鼓浪屿元宇宙”,能否成为中国文旅产业的“升级样本”

Zhongang Mining: the new energy industry is developing rapidly, and fluorine chemical products have a strong momentum

redis的string类型及bitmap

“寻源到结算“与“采购到付款“两者有什么不同或相似之处?
![ROS2安装时出现Connection failed [IP: 91.189.91.39 80]](/img/7f/92b7d44cddc03c58364d8d3f19198a.png)
ROS2安装时出现Connection failed [IP: 91.189.91.39 80]

网络IO总结文
随机推荐
Realize SKU management in the background
Background image related applications - full, adaptive
What are the differences or similarities between "demand fulfillment to settlement" and "purchase to payment"?
The following license SolidWorks Standard cannot be obtained, and the use license file cannot be found. (-1,359,2)。
Linear list (sequential storage, chain storage) (linked list of leading nodes, linked list of non leading nodes)
redis 网络IO
Realization of background channel group management function
02 linear structure 3 reversing linked list
Day3 -- flag state holding, exception handling and request hook
Login to homepage function implementation
JWT authentication and login function implementation, exit login
691. 立方体IV
Cenos7 update MariaDB
Node installation and debugging
数智革新
Include error in vs Code (new header file)
Eval and assert execute one sentence Trojan horse
Openresty + keepalived to achieve load balancing + IPv6 verification
4278. Summit
First experience of tryme in opengauss