当前位置:网站首页>NIO示例
NIO示例
2022-07-27 08:38:00 【芒骁】

服务端
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("服务器启动");
}
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("接收到客户连接,来自:" + 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("关闭与客户的连接");
}
}
}
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();
}
}
客户端
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("与服务器的连接建立成功");
}
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();
}
}
}
}
边栏推荐
- Realize SPU management in the background
- 如何在qsim查看软件对象的实例?
- Explain cache consistency and memory barrier
- Minio installation and use
- sql_ Mode strict mode (ansi/traditional/strict_trans_tables)
- 【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发1/100
- [ciscn2019 southeast China division]web11 1
- 4275. Dijkstra序列
- 好吃难吃饱七分为宜;好喝难喝醉三分为佳
- JWT authentication and login function implementation, exit login
猜你喜欢

How to view instances of software objects in QSIM?

低成本、低门槛、易部署,4800+万户中小企业数字化转型新选择

First experience of tryme in opengauss

One book 1201 Fibonacci sequence

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

It's better to be full than delicious; It's better to be drunk than drunk

开怀一笑

User management - restrictions

Solution to the program design of the sequence structure of one book (Chapter 1)

User management - restrictions
随机推荐
arguments
Process control - Branch
Pass parameters and returned responses of flask
无法获取下列许可SOLIDWORKS Standard,无法找到使用许可文件。(-1,359,2)。
User management - restrictions
【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发1/100
Block, there is a gap between the block elements in the row
[BJDCTF2020]EasySearch 1
General view, DRF view review
Arm undefined instruction exception assembly
3311. 最长算术
Implementation of registration function
After downloading URL loader and specifying the size of the image with limit, the image will not be displayed
Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?
[uni app advanced practice] take you hand-in-hand to learn the development of a purely practical complex project 1/100
Day4 --- flask blueprint and rest ful
众昂矿业:新能源行业快速发展,氟化工产品势头强劲
Fluent rendering mechanism - GPU thread rendering
Vcenter7.0 managing esxi7.0 hosts
View 的滑动冲突