Java 4---網路程式設計
阿新 • • 發佈:2018-12-22
導讀
1.計算機網路簡介
2.基於TCP協議的Socket程式設計
計算機網路簡介
基於TCP協議的Socket程式設計
HandleThread.java
package com.hala.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class HandleThread extends Thread { private Socket socket; BufferedReader brSocket; public HandleThread (Socket socket){ this.socket=socket; try { //獲取輸入流 //這裡之所以放在構造方法裡,就是要保證socket已經被賦值 brSocket=new BufferedReader( new InputStreamReader(socket.getInputStream())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 負責處理伺服器和每一個客戶機的互動 * 一個客戶機一個執行緒 */ @Override public void run() { try { String line=brSocket.readLine(); System.out.println("收到:"+line); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //關閉資源 try { brSocket.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
TCPServer.java
package com.hala.net; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) { // TODO Auto-generated method stub try { //1.建立ServerSocket,傳入一個埠號 ServerSocket serverSocket=new ServerSocket(6666); while(true){ //2.接收使用者的請求 //連線成功返回socket與客戶端互動,否則阻塞 Socket socket=serverSocket.accept(); //互動 //getInetAddress()返回此連線的遠端IP地址 是 InetAddress物件 //getHostAddress()是將結果作為字串返回 System.out.println(socket.getInetAddress().getHostAddress() +"連線成功"); //開闢一個新的執行緒,負責互動 HandleThread thread=new HandleThread(socket); thread.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
TCPClient.java
package com.hala.net; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class TCPClient { public static void main(String[] args) { // TODO Auto-generated method stub Socket socket=null; PrintWriter pw=null; Scanner input=new Scanner(System.in); try { //與伺服器建立連線,指定IP和埠號 socket=new Socket("172.31.0.1",6666); //為socket建立一個輸出通道,true的作用是重新整理快取 pw=new PrintWriter(socket.getOutputStream(),true); while(true){ System.out.println("請輸入:"); String line=input.next(); pw.println(line); //可以多次傳送的技巧 if(line.equals("exit")){ break; } } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(pw!=null){ pw.close(); } if(socket!=null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }