溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java如何共享Socket會話

發(fā)布時間:2022-05-23 15:52:36 來源:億速云 閱讀:210 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“Java如何共享Socket會話”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

一個優(yōu)秀的網(wǎng)絡(luò)服務(wù)程序除了能處理用戶的輸入信息,還必須能夠同時響應(yīng)多個客戶端的連接請求。在Java Socket會話中,實現(xiàn)以上功能特點是非常容易的。

設(shè)計原理:

主程序監(jiān)聽一端口,等待客戶接入;同時構(gòu)造一個線程類,準備接管會話。當(dāng)一個Java Socket會話產(chǎn)生后,將這個會話交給線程處理,然后主程序繼續(xù)監(jiān)聽。運用Thread類或Runnable接口來實現(xiàn)是不錯的辦法。

{實現(xiàn)消息共享}

  1. import java.io.*;  

  2. import java.net.*;  

  3. public class Server extends ServerSocket  

  4. {  

  5. private static final int SERVER_PORT = 10000;  

  6. public Server() throws IOException  

  7. {  

  8. super(SERVER_PORT);  

  9. try  

  10. {  

  11. while (true)  

  12. {  

  13. Socket socket = accept();  

  14. new CreateServerThread(socket);  

  15. }  

  16. }  

  17. catch (IOException e)  

  18. {}  

  19. finally  

  20. {  

  21. close();  

  22. }  

  23. }  

  24. //--- CreateServerThread  

  25. class CreateServerThread extends Thread  

  26. {  

  27. private Socket client;  

  28. private BufferedReader in;  

  29. private PrintWriter out;  

  30. public CreateServerThread(Socket s) throws IOException  

  31. {  

  32. client = s;  

  33. in = new BufferedReader(new InputStreamReader(client.
    getInputStream(), "GB2312"));  

  34. out = new PrintWriter(client.getOutputStream(), true);  

  35. out.println("--- Welcome ---");  

  36. start();  

  37. }  

  38. public void run()  

  39. {  

  40. try  

  41. {  

  42. String line = in.readLine();  

  43. while (!line.equals("bye"))  

  44. {  

  45. String msg = createMessage(line);  

  46. out.println(msg);  

  47. line = in.readLine();  

  48. }  

  49. out.println("--- See you, bye! ---");  

  50. client.close();  

  51. }  

  52. catch (IOException e)  

  53. {}  

  54. }  

  55. private String createMessage(String line)  

  56. {  

  57. xxxxxxxxx;  

  58. }  

  59. }  

  60. public static void main(String[] args) throws 
    IOException  

  61. {  

  62. new Server();  

  63. }  

“Java如何共享Socket會話”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI