Java review--NIO例項:實現服務端和客戶端的簡單通訊
客戶端程式碼:
package nio;
import java.io.IOException;
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.util.Iterator;
import java.util.Set;
public class NIOServer {
private int flag =1;
private int blockSize=4096;
private ByteBuffer sendbuffer =ByteBuffer.allocate(blockSize);//傳送資料緩衝區
private ByteBuffer receivebuffer =ByteBuffer.allocate(blockSize);//接收資料緩衝區
private Selector selector;//選擇器
public NIOServer(int port) throws IOException{
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
//設定是否組阻塞
serverSocketChannel.configureBlocking(false);
//建立客戶端和服務端的socket.socket網路套接字,用來向網路傳送請求,或者應答請求。
ServerSocket serverSocket=serverSocketChannel.socket();
//繫結socket地址,IP埠
serverSocket.bind(new InetSocketAddress(port));
//開啟篩選器
selector=Selector.open();
// 將選擇器繫結到監聽通道,只有非阻塞通道才可以註冊選擇器.並在註冊過程中指出該通道可以進行Accept操作,返回key
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server start ->"+port);
}
//NIOServer的監聽事件
public void listen() throws IOException{
while(true){
selector.select();
Set<SelectionKey> selectionKeys=selector.selectedKeys();
Iterator<SelectionKey> itetor=selectionKeys.iterator();
while(itetor.hasNext()){
//負責多執行緒併發的安全的key
SelectionKey selectionKey=itetor.next();
itetor.remove();
//業務邏輯
handleKey(selectionKey);
}
}
}
//業務邏輯
public void handleKey(SelectionKey selectionKey) throws IOException{
//服務端監聽通道
ServerSocketChannel server=null;
SocketChannel client=null;
String reciveText;
String sendText;
int count=0;
if(selectionKey.isAcceptable()){
//服務端接收客戶端資訊
server=(ServerSocketChannel)selectionKey.channel();
client=server.accept();
client.configureBlocking(false);
client.register(selector, selectionKey.OP_READ);
}else if(selectionKey.isReadable()){
//服務端讀取客戶端資訊
client =(SocketChannel)selectionKey.channel();
count =client.read(receivebuffer);
if(count>0){
reciveText =new String(receivebuffer.array(),0,count);
System.out.println("服務端接收到客戶端的資訊:"+reciveText);
client.register(selector,selectionKey.OP_WRITE);
}
}else if (selectionKey.isWritable()){
//服務端傳送資料給客戶端
sendbuffer.clear();
client=(SocketChannel)selectionKey.channel();
sendText="mag send to client:"+flag++;
sendbuffer.put(sendText.getBytes());
sendbuffer.flip();
client.write(sendbuffer);
System.out.println("服務端傳送資料給客戶端:"+sendText);
}
}
public static void main(String[] args) throws IOException {
int port =7080;
NIOServer server =new NIOServer(port);
server.listen();
}
}
服務端程式碼:
package nio;
import java.io.IOException;
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.util.Iterator;
import java.util.Set;
public class NIOClient {
private static int flag =1;
private static int blockSize=4096;
private static ByteBuffer sendbuffer =ByteBuffer.allocate(blockSize);//傳送資料緩衝區
private static ByteBuffer receivebuffer =ByteBuffer.allocate(blockSize);//接收資料緩衝區
//Socket地址:ip+埠
private final static InetSocketAddress serverAddress=new InetSocketAddress("127.0.0.1",7080);
public static void main(String[] args) throws IOException {
//開啟通道
SocketChannel socketChannel=SocketChannel.open();
//通道設定成非阻塞模式
socketChannel.configureBlocking(false);
//開啟篩選器
Selector selector =Selector.open();
//註冊選擇器
socketChannel.register(selector, SelectionKey.OP_CONNECT);
socketChannel.connect(serverAddress);
Set<SelectionKey> selectionKeys;
Iterator<SelectionKey> iterator;
SelectionKey selectionKey;
SocketChannel client;
String receiveTest;
String sendText;
int count=0;
while(true){
selectionKeys =selector.selectedKeys();
iterator=selectionKeys.iterator();
while(iterator.hasNext()){
selectionKey=iterator.next();
if(selectionKey.isConnectable()){
System.out.println("client connect");
client =(SocketChannel)selectionKey.channel();
if(client.isConnectionPending()){
client.finishConnect();
System.out.println("客戶端完成連線操作!");
sendbuffer.clear();
sendbuffer.put("Hello,Server".getBytes());
sendbuffer.flip();
client.write(sendbuffer);
}
client.register(selector, SelectionKey.OP_READ);
}if(selectionKey.isReadable()){
client=(SocketChannel)selectionKey.channel();
receivebuffer.clear();
count=client.read(receivebuffer);
if(count>0){
receiveTest =new String(receivebuffer.array(),0,count);
System.out.println("客戶端接收到服務端的資料:"+receiveTest);
client.register(selector,SelectionKey.OP_WRITE);
}
}if(selectionKey.isWritable()){
sendbuffer.clear();
client=(SocketChannel)selectionKey.channel();
sendText="Msg from client--->"+flag++;
sendbuffer.put(sendText.getBytes());
sendbuffer.flip();
client.write(sendbuffer);
System.out.println("客戶端傳送方資料給服務端:"+sendText);
client.register(selector, SelectionKey.OP_READ);
}
}
selectionKeys.clear();
}
}
}
相關文章
- Socket最簡單的客戶端與服務端通訊-Java客戶端服務端Java
- 實現客戶端與服務端的HTTP通訊客戶端服務端HTTP
- SHA-256加密簡單例項(客戶端、服務端)加密單例客戶端服務端
- TCP通訊客戶端和服務端簡單程式碼實現TCP客戶端服務端
- binder通訊例項之c++客戶端與c++服務端C++客戶端服務端
- PHP-Socket服務端客戶端傳送接收通訊例項詳解PHP服務端客戶端
- ElasticSearch客戶端簡單操作例項Elasticsearch客戶端
- 基於node的tcp客戶端和服務端的簡單通訊TCP客戶端服務端
- 客戶端與服務端Socket通訊原理詳解客戶端服務端
- Java的oauth2.0 服務端與客戶端的實現JavaOAuth服務端客戶端
- [精華][推薦]CAS SSO單點登入服務端客戶端例項服務端客戶端
- AgileEAS.NET SOA 中介軟體平臺.Net Socket通訊框架-簡單例子-實現簡單的服務端客戶端訊息應答框架單例服務端客戶端
- Java建立WebService服務及客戶端實現JavaWeb客戶端
- golang實現tcp客戶端服務端程式GolangTCP客戶端服務端
- 實現服務端和客戶端的實時雙向資料傳輸-WebSocket簡單瞭解服務端客戶端Web
- zeroc ice 客戶端與服務端通訊例子(c++)客戶端服務端C++
- Java建立WebService服務及客戶端實現(轉)JavaWeb客戶端
- 服務端渲染和客戶端渲染服務端客戶端
- Android實現Thrift服務端與客戶端Android服務端客戶端
- windows socket簡單使用--實現客戶端連結服務端併傳送和接收資料Windows客戶端服務端
- TCP/UDP簡易通訊框架原始碼,支援輕鬆管理多個TCP服務端(客戶端)、UDP客戶端TCPUDP框架原始碼服務端客戶端
- HTML轉PDF的純客戶端和純服務端實現方案HTML客戶端服務端
- SSLSocket實現服務端和客戶端雙向認證的例子服務端客戶端
- 遠端終端服務的簡單實現
- linux網路程式設計之用socket實現簡單客戶端和服務端的通訊(基於TCP)Linux程式設計客戶端服務端TCP
- Spring Boot 整合 WebSocket 實現服務端推送訊息到客戶端Spring BootWeb服務端客戶端
- ZooKeeper服務發現客戶端客戶端
- C++20協程例項:攜程化的IOCP服務端/客戶端C++服務端客戶端
- Java服務端和客戶端開發輔助工具UtilsJava服務端客戶端
- node.js實現的簡單udp廣播伺服器和客戶端程式碼例項Node.jsUDP伺服器客戶端
- python建立tcp服務端和客戶端PythonTCP服務端客戶端
- Qt實現網路聊天室(客戶端,服務端)QT客戶端服務端
- Rest Post示例(java服務端、python客戶端)RESTJava服務端Python客戶端
- 如何用Java Socket實現一個簡單的Redis客戶端JavaRedis客戶端
- 極簡的Restful框架推薦->Resty(服務端+客戶端)REST框架服務端客戶端
- springboot2整合websocket,實現服務端推送訊息到客戶端Spring BootWeb服務端客戶端
- 使用Apollo Server搭建GraphQL的服務端和客戶端Server服務端客戶端
- Go基於gRPC實現客戶端連入服務端GoRPC客戶端服務端