Java基于Socket實(shí)現(xiàn)簡(jiǎn)單的多線程回顯服務(wù)器功能示例
本文實(shí)例講述了Java基于Socket實(shí)現(xiàn)簡(jiǎn)單的多線程回顯服務(wù)器功能。分享給大家供大家參考,具體如下:
需要兩個(gè)類,一個(gè)是EchoServer,代表服務(wù)器。另外一個(gè)是EchoServerClient,代表客戶端。代碼如下:
package interview; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class EchoServer { public static void main(String []args) throws IOException{ ServerSocket server = new ServerSocket(6789); while(true){ Socket client = server.accept(); ClientHandler handler = new ClientHandler(client); new Thread(handler).start(); } } public static class ClientHandler implements Runnable{ private Socket client; @Override public void run() { InputStreamReader isr = null; try { isr = new InputStreamReader(client.getInputStream()); BufferedReader br = new BufferedReader(isr); PrintWriter pw = new PrintWriter(client.getOutputStream()); String msg = br.readLine(); System.out.println("收到" + client.getInetAddress() + "發(fā)送的" + msg); pw.println("收到了你發(fā)的" + msg); pw.flush(); } catch (IOException e) { e.printStackTrace(); } } public ClientHandler(Socket client){ this.client = client; } } }
下面是客戶端代碼:
package interview; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class EchoServerClient { public static void main(String []args) throws UnknownHostException, IOException{ Socket client = new Socket("127.0.0.1", 6789); Scanner sc = new Scanner(System.in); System.out.print("請(qǐng)輸入要發(fā)送的內(nèi)容:"); String msg = sc.nextLine(); sc.close(); PrintWriter pw = new PrintWriter(client.getOutputStream()); pw.println(msg); pw.flush(); InputStreamReader isr = new InputStreamReader(client.getInputStream()); BufferedReader br = new BufferedReader(isr); System.out.println("服務(wù)器返回:" + br.readLine()); client.close(); } }
NIO多路復(fù)用套接字方法如下:
package interview; import java.io.IOException; 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.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.util.Iterator; public class EchoServerNIO { private static ServerSocketChannel serverChannel = null; private static Selector selector = null;// 多路復(fù)用選擇器 private static ByteBuffer buffer = null; // 緩沖區(qū) public static void main(String []args) throws IOException{ init(); listen(); } static void init() throws IOException{ serverChannel = ServerSocketChannel.open(); buffer = ByteBuffer.allocate(1024); serverChannel.socket().bind(new InetSocketAddress(6789)); serverChannel.configureBlocking(false); selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); } static void listen() throws IOException{ while(true){ if(selector.select(5000) != 0){ Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while(it.hasNext()){ SelectionKey key = it.next(); it.remove(); handleKey(key); } } } } static void handleKey(SelectionKey key) throws IOException{ SocketChannel channel = null; if(key.isAcceptable()){ ServerSocketChannel serverChannel = (ServerSocketChannel)key.channel(); channel = serverChannel.accept(); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); }else if(key.isReadable()){ channel = (SocketChannel)key.channel(); buffer.clear(); if(channel.read(buffer) > 0){ buffer.flip(); CharBuffer charBuffer = CharsetHelper.decode(buffer); String msg = charBuffer.toString(); System.out.println("收到" + channel.getRemoteAddress() + "的消息:" + msg); channel.write(CharsetHelper.encode(CharBuffer.wrap("received your msg:" + msg))); } } } public static class CharsetHelper{ private static final String UTF_8 = "UTF-8"; private static CharsetEncoder encoder = Charset.forName(UTF_8).newEncoder(); private static CharsetDecoder decoder = Charset.forName(UTF_8).newDecoder(); private CharsetHelper() { } public static ByteBuffer encode(CharBuffer in) throws CharacterCodingException{ return encoder.encode(in); } public static CharBuffer decode(ByteBuffer in) throws CharacterCodingException{ return decoder.decode(in); } } }
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java Socket編程技巧總結(jié)》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章
Java異常處理中同時(shí)有finally和return語句的執(zhí)行問題
這篇文章主要介紹了Java異常處理中同時(shí)有finally和return語句的執(zhí)行問題,首先確定的是一般finally語句都會(huì)被執(zhí)行...然后,需要的朋友可以參考下2015-11-11SpringBoot中Bean拷貝及工具類封裝的實(shí)現(xiàn)
本文主要介紹了SpringBoot中Bean拷貝及工具類封裝的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05Java 8中Stream API的這些奇技淫巧!你Get了嗎?
這篇文章主要介紹了Java 8中Stream API的這些奇技淫巧!你Get了嗎?文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Java讀取properties配置文件時(shí),出現(xiàn)中文亂碼的解決方法
下面小編就為大家?guī)硪黄狫ava讀取properties配置文件時(shí),出現(xiàn)中文亂碼的解決方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-11-11Java?web實(shí)現(xiàn)頭像上傳以及讀取顯示
這篇文章主要為大家詳細(xì)介紹了Java?web實(shí)現(xiàn)頭像上傳以及讀取顯示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06Java編程基于快速排序的三個(gè)算法題實(shí)例代碼
這篇文章主要介紹了Java編程基于快速排序的三個(gè)算法題實(shí)例代碼,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01