用java.net包建立雙向通訊

來源:互聯網
上載者:User

利用java.net包提供的網路能力。以有串連流通訊方式為例,

在伺服器端的操作為一般為:

   ⑴ 建立一個ServerSocket對象,在指定連接埠監聽用戶端發來的請求。

   ⑵ 在接收到請求時accept()方法將返回一個Socket對象。

   ⑶ 用上述Socket對象建立輸入、輸出資料流對象。

   ⑷ 通過輸入、輸出資料流與客戶互動。

   ⑸ 互動完畢,關閉輸入、輸出資料流與Socket。

   ⑹ 服務程式運行結束,關閉ServerSocket。

   實現代碼代碼類如:

try{

boolean flag=true;
Socket clientSocket=null;

ServerSocket serverSocket = new ServerSocket(0);
System.out.println("Server listen on: " +serverSocket.getLocalPort());

while(flag){
clientSocket=serverSocket.accept();
DataInputStream is=new DataInputStream( new bufferedInputStream(client
Socket.getInputStream()));
PrintStream os=new PrintStream( new bufferedOutputStream(clientSocket.
getOutputStream()));
// 處理Applet請求
os.close();
is.close();
clientSocket.close();
}
serverSocket.close();
}catch( IOException e){
System.err.println(" Exception: "+e);
}

   在用戶端的操作為:

   ⑴ 建立Socket對象建立與伺服器的串連。

   ⑵ 用該Socket對象建立輸入、輸出資料流。

   ⑶ 與伺服器互動。

   ⑷ 互動完畢,關閉輸入、輸出資料流與Socket。

   實現代碼類如:

try {
Socket clientSocket =new Socket("serverName",7);
OutputStream os=clientSocket.getOutputStream();
DataInputStream is=new DataInputStream( clientSocket.getInputStream())
;
// 其它操作.
os.close();
is.close();
clientSocket.close();
}catch(Exception e){
System.err.println("Exception:"+e);
}

   這種方法只依賴於標準的Java網路支援,不需要用到附加的軟體包或工具,
因此顯得相當簡潔和靈活,易於實現某些特殊的需要。

來自:http://www.javah.net/wangluobiancheng/20070605/2330.html

相關文章

聯繫我們

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