用Java Socket開發支援上千個並發的小型伺服器(下)

來源:互聯網
上載者:User

總結一下客戶機

我們的類研究完了。在我們繼續往前討論區伺服器端的情況之前,讓我們回顧一下建立和使用Socket的步驟:

1.用您想串連的機器的IP地址和連接埠執行個體化Socket(如有問題則拋出Exception)。

2.擷取Socket上的流以進行讀寫。

3.把流封裝進BufferedReader/PrintWriter的執行個體,如果這樣做能使事情更簡單的話。

4.對Socket進行讀寫。

5.關閉開啟的流。

5建立伺服器Socket

建立RemoteFileServer類

1.import java.io.*;
2.import java.net.*;
3.public class RemoteFileServer {
4. int listenPort;
5. public RemoteFileServer(int listenPort) {
6. this.listenPort=listenPort;
7. }
8. //允許客戶機串連到伺服器,等待客戶機請求
9. public void acceptConnections() {
10. try {
11. ServerSocket server = new ServerSocket(listenPort);
12. Socket incomingConnection = null;
13. while(true) {
14. incomingConnection = server.accept();
15. handleConnection(incomingConnection);
16. }
17. }
18. catch(BindException e) {
19. System.out.println("Unable to bind to port "+listenPort);
20. }
21. catch(IOException e) {
22. System.out.println("Unable to instantiate a ServerSocket on port: "+listenPort);
23.
24. }
25. }
26. //與客戶機Socket互動以將客戶機所請求的檔案的內容發送到客戶機
27. public void handleConnection(Socket incomingConnection) {
28. try {
29. OutputStream outputToSocket = incomingConnection.getOutputStream();
30. InputStream inputFromSocket = incomingConnection.getInputStream();
31. BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket));
32. FileReader fileReader = new FileReader(new File(streamReader.readLine()));
33. BufferedReader bufferedFileReader = new BufferedReader(fileReader);
34. PrintWriter streamWriter = new PrintWriter(incomingConnection.getOutputStream());
35. String line = null;
36. while((line=bufferedFileReader.readLine())!=null){
37. streamWriter.println(line);
38. }
39. fileReader.close();
40. streamWriter.close();
41. streamReader.close();
42. }
43. catch(Exception e) {
44. System.out.println("Error handling a client: "+e);
45. e.printStackTrace();
46. }
47. }
48. public static void main(String args[]) {
49. RemoteFileServer server = new RemoteFileServer(1001);
50. server.acceptConnections();
51. }
52.}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.