這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)Java項(xiàng)目中的多線程通信如何利用Socket實(shí)現(xiàn),文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
成都創(chuàng)新互聯(lián)主要為客戶提供服務(wù)項(xiàng)目涵蓋了網(wǎng)頁視覺設(shè)計、VI標(biāo)志設(shè)計、全網(wǎng)整合營銷推廣、網(wǎng)站程序開發(fā)、HTML5響應(yīng)式重慶網(wǎng)站建設(shè)公司、手機(jī)網(wǎng)站制作設(shè)計、微商城、網(wǎng)站托管及成都網(wǎng)站改版、WEB系統(tǒng)開發(fā)、域名注冊、國內(nèi)外服務(wù)器租用、視頻、平面設(shè)計、SEO優(yōu)化排名。設(shè)計、前端、后端三個建站步驟的完善服務(wù)體系。一人跟蹤測試的建站服務(wù)標(biāo)準(zhǔn)。已經(jīng)為電動窗簾行業(yè)客戶提供了網(wǎng)站維護(hù)服務(wù)。
Java Socket實(shí)現(xiàn)多線程通信的方法,代碼如下:
package com.googlecode.garbagecan.test.socket.sample2; 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 MyServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(10000); while (true) { Socket socket = server.accept(); invoke(socket); } } private static void invoke(final Socket client) throws IOException { new Thread(new Runnable() { public void run() { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream()); while (true) { String msg = in.readLine(); System.out.println(msg); out.println("Server received " + msg); out.flush(); if (msg.equals("bye")) { break; } } } catch(IOException ex) { ex.printStackTrace(); } finally { try { in.close(); } catch (Exception e) {} try { out.close(); } catch (Exception e) {} try { client.close(); } catch (Exception e) {} } } }).start(); } }
下面是Client程序代碼:
package com.googlecode.garbagecan.test.socket.sample2; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class MyClient { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 10000); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = reader.readLine(); out.println(msg); out.flush(); if (msg.equals("bye")) { break; } System.out.println(in.readLine()); } socket.close(); } }
測試,首先運(yùn)行MyServer類,然后運(yùn)行兩個MyClient類,然后分別在每個MyClient的提示符下輸入字符串,就可以看到Server可以分別接收處理每個Client的請求了。
上述就是小編為大家分享的Java項(xiàng)目中的多線程通信如何利用Socket實(shí)現(xiàn)了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。