《Java程式設計》第三次作業:網路編程

來源:互聯網
上載者:User

標籤:

作業的目標

    目標1:Socket簡單應用。  把教材P238-230中例11-5代碼輸入到我們的代碼編輯器,調試並運行(80分)。

P238用戶端程式

import java.io.*;import java.net.*;public class ChatClient {public static void main(String args[]){try{Socket socket=new Socket("127.0.0.1",4001);System.out.println("輸入你要說的話,如果要退出輸入bye");BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));PrintWriter os=new PrintWriter(socket.getOutputStream());BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));String readline;readline =sin.readLine();while(! readline.equals("bye")){os.println(readline);os.flush();System.out.println("Client:"+readline);System.out.println("Server:"+is.readLine());readline=sin.readLine();}os.close();is.close();socket.close();}catch(Exception e){System.out.println("Error"+e);}}}



P238-230 伺服器端程式

import java.io.*;import java.net.*;import java.applet.Applet;public class ChatServer {public static void main(String args[]){try{ServerSocket server=null;try{server=new ServerSocket(4001);System.out.println("準備好了,退出輸入bye");}catch(Exception e){System.out.println("can not listen to:"+e);}Socket socket=null;try{socket=server.accept();}catch(Exception e){System.out.println("Error."+e);}String line;BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));PrintWriter os=new PrintWriter(socket.getOutputStream());BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));System.out.println("Client:"+is.readLine());line=sin.readLine();while(! line.equals("bye")){os.print(line);os.flush();System.out.println("Client:"+is.readLine());line=sin.readLine();}os.close();is.close();socket.close();server.close();}catch(Exception e){System.out.println("Error:"+e);}}}


《Java程式設計》第三次作業:網路編程

聯繫我們

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