以下實例示範如何使用Socket 類別的accept() 方法和ServerSocket 類別的MultiThreadServer(socketname) 方法來實作多執行緒伺服器程式:
/* author by w3cschool.cc MultiThreadServer.java */import java.io.IOException;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;public class MultiThreadServer implements Runnable { Socket csocket; MultiThreadServer(Socket csocket) { this.csocket = csocket; } public static void main(String args[]) throws Exception { ServerSocket ssock = new ServerSocket(1234); System.out.println("Listening"); while (true) { Socket sock = ssock.accept(); System.out.println("Connected"); new Thread(new MultiThreadServer(sock)).start(); } } public void run() { try { PrintStream pstream = new PrintStream (csocket.getOutputStream()); for (int i = 100; i >= 0; i--) { pstream.println(i + " bottles of beer on the wall"); } pstream.close(); csocket.close(); } catch (IOException e) { System.out.println(e); } }}
就是以上程式碼執行輸出結果為:
Listening Connected
就是上述程式碼結果為以上Socket 實作多執行緒伺服器程式的內容,更多相關內容請關注PHP中文網(www.php.cn)!