您好,登錄后才能下訂單哦!
小編給大家分享一下如何使用java實現客戶端與服務器,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
Java主要應用于:1. web開發;2. Android開發;3. 客戶端開發;4. 網頁開發;5. 企業級應用開發;6. Java大數據開發;7.游戲開發等。
開啟多個客戶端
服務端效果:
客戶端效果:
當一個客戶端斷開連接:
因為代碼中有注釋,我就直接貼上來了
服務端:
package com.dayrain.server; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets; import java.util.Iterator; public class NioServer { /**端口**/ private static final int PORT = 8081; /**buffer大小**/ private static final int DEFAULT_BUFFER_SIZE = 1024; private final Selector selector; private final ByteBuffer readBuffer = ByteBuffer.allocate(NioServer.DEFAULT_BUFFER_SIZE); private final ByteBuffer writeBuffer = ByteBuffer.allocate(NioServer.DEFAULT_BUFFER_SIZE); private static int count = 0; public static void main(String[] args) throws IOException { new NioServer().start(); } public NioServer() throws IOException { //創建一個服務端channel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //設置為非阻塞 serverSocketChannel.configureBlocking(false); //獲取服務器socket ServerSocket socket = serverSocketChannel.socket(); //綁定ip和端口 socket.bind(new InetSocketAddress(NioServer.PORT)); //創建多路復用選擇器,并保持打開狀態,直到close selector = Selector.open(); //將服務器管道注冊到selector上,并監聽accept事件 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("server start on port: " + NioServer.PORT); start(); } public void start() throws IOException { //selector是阻塞的,直到至少有一個客戶端連接。 while (selector.select() > 0) { //SelectionKey是channel想Selector注冊的令牌,可以通過chancel取消(不是立刻取消,會放進一個cancel list里面,下一次select時才會把它徹底刪除) Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); //當這個key的channel已經準備好接收套接字連接 if(selectionKey.isAcceptable()) { connectHandle(selectionKey); } //當這個key的channel已經準備好讀取數據時 if(selectionKey.isReadable()) { readHandle(selectionKey); } } } } /** * 處理連接 * @param selectionKey */ private void connectHandle(SelectionKey selectionKey) throws IOException { //注意,服務端用的是ServerSocketChannel,BIO中是ServerSocket ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); if(socketChannel == null) { return; } socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE); System.out.println("客戶端連接成功,當前總數:" + (++count)); writeBuffer.clear(); writeBuffer.put("連接成功".getBytes(StandardCharsets.UTF_8)); writeBuffer.flip(); socketChannel.write(writeBuffer); } /** * 讀取數據 * @param selectionKey */ private void readHandle(SelectionKey selectionKey){ SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); try { readBuffer.clear(); int read = socketChannel.read(readBuffer); if(read > 0) { readBuffer.flip(); String receiveData = StandardCharsets.UTF_8.decode(readBuffer).toString(); System.out.println("收到客戶端消息: " + receiveData); writeBuffer.clear(); writeBuffer.put(receiveData.getBytes(StandardCharsets.UTF_8)); writeBuffer.flip(); socketChannel.write(writeBuffer); } }catch (Exception e) { try { socketChannel.close(); } catch (IOException ioException) { ioException.printStackTrace(); } System.out.println("客戶端斷開了連接~~"); count--; } } }
客戶端
package com.dayrain.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; 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.StandardCharsets; import java.util.Iterator; public class NioClient { private static final int PORT = 8081; private static final int DEFAULT_BUFFER_SIZE = 1024; private final Selector selector; private final ByteBuffer readBuffer = ByteBuffer.allocate(NioClient.DEFAULT_BUFFER_SIZE); private final ByteBuffer writeBuffer = ByteBuffer.allocate(NioClient.DEFAULT_BUFFER_SIZE); public static void main(String[] args) throws IOException { NioClient nioClient = new NioClient(); //終端監聽用戶輸入 new Thread(nioClient::terminal).start(); //這個方法是阻塞的,要放在最后 nioClient.start(); } public NioClient() throws IOException { selector = Selector.open(); SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(InetAddress.getLocalHost(), NioClient.PORT)); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); } public void start() throws IOException { while (selector.select() > 0) { Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); //拿到selectionKey后要刪除,否則會重復處理 iterator.remove(); if(selectionKey.isReadable()) { handleRead(selectionKey); } //只要連接成功,selectionKey.isWritable()一直為true if(selectionKey.isWritable()) { handleWrite(selectionKey); } } } } /** * 監聽寫操作 */ private void handleWrite(SelectionKey selectionKey) throws IOException { SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); // writeBuffer有數據就直接寫入,因為另開了線程監聽用戶讀取,所以要上鎖 synchronized (writeBuffer) { writeBuffer.flip(); while (writeBuffer.hasRemaining()) { socketChannel.write(writeBuffer); } writeBuffer.compact(); } } /** * 監聽讀操作 */ private void handleRead(SelectionKey selectionKey) throws IOException { SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); readBuffer.clear(); socketChannel.read(readBuffer); readBuffer.flip(); String res = StandardCharsets.UTF_8.decode(readBuffer).toString(); System.out.println("收到服務器發來的消息: " + res); readBuffer.clear(); } /** * 監聽終端的輸入 */ private void terminal() { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); try { String msg; while ((msg = bufferedReader.readLine()) != null) { synchronized (writeBuffer) { writeBuffer.put((msg + "\r\n").getBytes(StandardCharsets.UTF_8)); } } }catch (Exception e) { e.printStackTrace(); } } }
以上是“如何使用java實現客戶端與服務器”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。