Java - TCP網路編程

來源:互聯網
上載者:User

標籤:local   static   ror   out   style   equals   kth   err   next   

Java - TCP網路編程Server

邏輯思路:

  1. 建立ServerSocket(port),然後伺服器的socket就啟動了
  2. 迴圈中調用accept(),此方法會堵塞程式,直到發現使用者請求,返回使用者的socket
  3. 利用多線程對使用者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

邏輯思路:

  1. 建立Socket(IP, port),其參數為目標伺服器的IP和port
  2. 然後就可以通過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網路編程

聯繫我們

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