Java Socket實戰之二 多線程通訊

來源:互聯網
上載者:User

本文地址:http://blog.csdn.net/kongxx/article/details/7259465

Java Socket實戰之一 單線程通訊

上一篇文章說到怎樣寫一個最簡單的Java Socket通訊,但是在上一篇文章中的例子有一個問題就是Server只能接受一個Client請求,當第一個Client串連後就佔據了這個位置,後續Client不能再繼續串連,所以需要做些改動,當Server沒接受到一個Client串連請求之後,都把處理流程放到一個獨立的線程裡去運行,然後等待下一個Client串連請求,這樣就不會阻塞Server端接收請求了。每個獨立啟動並執行程式在使用完Socket對象之後要將其關閉。具體代碼如下:

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();}}

測試,首先運行MyServer類,然後運行兩個MyClient類,然後分別在每個MyClient的提示符下輸入字串,就可以看到Server可以分別接收處理每個Client的請求了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.