IO鐢ㄦ硶鍑犱緥
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IO鐢ㄦ硶鍑犱緥相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/http' title='http'>http each soc alt string puts 闃诲 catch info
涓€涓緥瀛?/p>
public class DemoServer extends Thread { private ServerSocket serverSocket; public int getPort() { return serverSocket.getLocalPort(); } @Override public void run() { try { serverSocket = new ServerSocket(0);銆€銆€銆€銆€// 缁戝畾0绔彛 while (true) { Socket socket = serverSocket.accept();銆€銆€銆€銆€銆€銆€// 璋冪敤accept鏂规硶锛岄樆濉炵瓑寰呭鎴风杩炴帴 RequestHandler requestHandler = new RequestHandler(socket); requestHandler.start(); } } catch (IOException e) { e.printStackTrace(); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { DemoServer server = new DemoServer(); server.start();銆€銆€銆€銆€銆€銆€銆€銆€ try (Socket client = new Socket(InetAddress.getLocalHost(), server.getPort())) {銆€銆€銆€銆€// 妯℃嫙socket瀹㈡埛绔? BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream())); bufferedReader.lines().forEach(s -> System.out.println(s)); } catch (Exception e) { e.printStackTrace(); } } } class RequestHandler extends Thread { private Socket socket; RequestHandler(Socket socket) { this.socket = socket; } @Override public void run() { try (PrintWriter out = new PrintWriter(socket.getOutputStream());) { out.println("hello"); out.flush(); } catch (Exception e) { e.printStackTrace(); } } }
绾跨▼鍚姩
姣忎釜閮藉紑涓€涓嚎绋嬭繃浜庢氮璐癸紝绾跨▼姹犳敼杩?/p>
serverSocket = new ServerSocket(0); executorService = Executors.newFixedThreadPool(8); while (true) { Socket socket = serverSocket.accept(); RequestHandler requestHandler = new RequestHandler(socket); // requestHandler.start(); executorService.execute(requestHandler); }
骞跺彂閲忎笉澶х殑鎯呭喌杩欑鍚屾闃诲鏂瑰紡鏄彲浠ョ殑锛屼絾鏄敱浜庣嚎绋嬬殑涓婁笅鏂囧垏鎹㈡槸搴熸€ц兘鐨勶紝鍦ㄩ珮骞跺彂鎯呭喌涓嬫樉鐒朵笉鍚堥€傘€?/p>
锛堝緟琛ュ厖锛?/p>
以上是关于IO鐢ㄦ硶鍑犱緥的主要内容,如果未能解决你的问题,请参考以下文章