標籤:local static ror out style equals kth err next
Java - TCP網路編程Server
邏輯思路:
- 建立ServerSocket(port),然後伺服器的socket就啟動了
- 迴圈中調用accept(),此方法會堵塞程式,直到發現使用者請求,返回使用者的socket
- 利用多線程對使用者socket進行IO操作
注意:對Scoket/File進行建立、關閉,都需要放try catch中,檢測 IOException,所以將網路IO部分整體放入try catch中即可。
1. 字串操作
輸出:PrintWriter out=new PrintWriter(sock.getOutputStream(), true);
讀取:BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
或者:Scanner input=new Scanner(sock.getInputStream());
2. 位元組操作(一般用於傳輸檔案,體積大,要求效率高,用BufferedInputStream/BufferedOutputStream)
輸出:BufferedOutputStream out=new BufferedOutputStream(sock.getOutputStream());
輸出:BufferedInputStream out=new BufferedInputStream(sock.getInputStream());
import java.io.*;import java.net.*;public class TCP_Server { public static void main(String[] args){ int port=8888; try { ServerSocket sock=new ServerSocket(port); System.out.println("伺服器啟動,Port:"+sock.getLocalPort()); while(true){ Socket client=sock.accept(); //***注意,accept()是個阻塞函數,返回client socket*** System.out.println("監測到TCP串連來自:"+client.getRemoteSocketAddress()); new WorkThread(client).start(); //多線程 } } catch (IOException e) { System.out.println("ERROR Found: "+e.getMessage()); } //end try catch }}class WorkThread extends Thread{ Socket sock; public WorkThread(Socket sock){ this.sock=sock; } public void run(){ try{ //此處用BufferedReader實現 BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream())); PrintWriter out=new PrintWriter(sock.getOutputStream(),true); String s=null; while((s=in.readLine())!=null){ //斷開會返回null if(s.equals("end")) break; System.out.println("收到:"+s); out.println("Server:"+s); } /*注意,readLine()是個阻塞函數,放在while((s=readLine())!=null)中會堵塞程式,等待使用者的資料。 *有兩種方式中斷迴圈 *1.使用者端斷開TCP程式,in.readLine()會返回null *2.使用者正常退出,使用者端發送個[結束標記]給伺服器,伺服器根據標記,中斷迴圈 */ System.out.println("監測到TCP串連來自:"+sock.getRemoteSocketAddress()+"已斷開。"); in.close(); out.close(); sock.close(); } catch(IOException e){ System.out.println(e.getMessage()); } } }
Client
邏輯思路:
- 建立Socket(IP, port),其參數為目標伺服器的IP和port
- 然後就可以通過Socket進行IO操作了
import java.net.*;import java.io.*;import java.util.*;public class TCP_Client { public static void main(String[] args) { Scanner in=new Scanner(System.in); try{ int port=8888; String ip="127.0.0.1"; Socket sock=new Socket(ip, port); //從socket中輸出 PrintWriter out=new PrintWriter(sock.getOutputStream(),true); //從socket中讀取,此處用Scanner實現 Scanner input=new Scanner(sock.getInputStream()); while(true){ System.out.print("請輸入訊息:"); String s=in.nextLine(); if(s.equals("end")){ out.println(s); break; } out.println(s); System.out.println("發送:"+s); s=input.nextLine(); System.out.println("收到:"+s); } in.close(); input.close(); out.close(); sock.close(); } catch (IOException e){ System.out.println("ERROR Found: "+e.getMessage()); } }}
Java - TCP網路編程