黑馬程序員_Java基礎_網絡編程

------- android培訓java培訓、期待與您交流! ----------


IP對應類 : InetAddress類

 此類表示互聯網協議IP地址
主機名到 IP 地址的解析 通過使用本地機器配置信息和網絡命名服務和網絡信息服務來實現。
要使用的特定命名服務默認情況下是本地機器配置的那個。
對於任何主機名稱,都返回其相應的 IP 地址。  
常用方法:
static InetAddress getLocalHost()  返回本地主機
 byte[] getAddress()  返回此 InetAddress 對象的原始 IP 地址
getHostName() 獲取此 IP 地址的主機名
getHostAddress() 返回 IP 地址字符串
static InetAddress getByAddress(String host, byte[] addr)  根據提供的主機名和 IP 地址創建 InetAddress
static InetAddress getByAddress(byte[] addr)    在給定原始 IP 地址的情況下,返回 InetAddress 對象
static InetAddress getAllByName(String host)  在給定主機名的情況下,根據系統上配置的名稱服務返回其 IP 地址所組成的數組

 

例子1:

<strong>public class IPDemo {
    public static void main(String[] args) throws UnknownHostException {
        // InetAddress i = InetAddress.getLocalHost();
        // System.out.println(i.toString());
        // System.out.println("Address:"+i.getHostAddress());
        // System.out.println("name:"+i.getHostName());
        //運行結果:mo/171.39.84.202
//      Address:171.39.84.202
//      name:mo
        
        // 百度可能有多個主機IP
        InetAddress[] i = InetAddress.getAllByName("www.baidu.com");
        for (InetAddress ia : i) {
            System.out.println("baidu--Address:" + ia.getHostAddress());
            System.out.println("baidu--name:" + ia.getHostName());
        }
//      運行結果:baidu--Address:112.80.248.74
//      baidu--name:www.baidu.com
//      baidu--Address:112.80.248.73
//      baidu--name:www.baidu.com
    }
}
</strong>

 需求:通過UDP傳輸方式  將一段文字數據發送出去。

 定義一個UDP發送端
 思路:
 1.建立udpsocket服務
 2.提供數據,並將數據封裝到數據包中
 3.通過socket服務的發送功能,將數據包發出去
 4.關閉資源。

發送端:
例子2:

<strong>public class UDPSentDemo {
    public static void main(String[] args) throws Exception {
        // 1.創建一個UDP服務, 通過DatagramSocket對象,並指定發送使用的端口號爲8888(如果不設置,系統隨機安排端口)
        DatagramSocket ds = new DatagramSocket(8888);
        // 2.確定數據,並封裝成數據包
        byte[] buf = "udp welcom to".getBytes();
        DatagramPacket dp = new DatagramPacket(buf, buf.length,
                InetAddress.getByName("171.39.84.202"), 10000);
        // 3. 發送
        ds.send(dp);
        // 4.關閉資源
        ds.close();
    }
}</strong>

接收端:

 需求:
 定義一個應用程序,用與接受UDP協議傳輸的數據並處理
 
 定義UDP的接收端。
 思路:
 1.定義UDP socket服務,通常會監聽一個端口,其實就是個這個接受網絡應用程序定義數字辨識。
 方便於明確那些數據過來該應用程序可以處理
 
 2.定義一個數據包,因爲要存儲接受到的字節數據。
 因爲數據包對象中有更多功能可以提取字節數據中的不同數據信息。
 
 3.通過socket服務的receive 方法將夠到的數據存入已定義好的數據包中。
 
 4.通過數據包對象的特有功能。將這些不同的數據取出,打印在控制檯上
 
 5。關閉資源。

例子3: 

<strong>public class UDPReceiveDemo {
    public static void main(String[] args) throws Exception {
        // 1.創建一個UDP服務, 通過DatagramSocket對象,並設置監聽的端口號10000
        DatagramSocket ds = new DatagramSocket(10000);
        // 2.定義數據包,接受數據包,並封裝成數據包
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        
        // 3. 接受數據,將收到的數據存入數據包中
        ds.receive(dp);    //阻塞式方法,沒收到數據時,將處於阻塞狀態
        // 將字節數組數據轉變成字符串
        String data = new String(dp.getData(), 0, dp.getLength());
        // 發送者的IP
        String address = dp.getAddress().getHostAddress();
        // 發送者發送使用的端口號
        int port = dp.getPort();
        System.out.println("send IP:" + address);
        System.out.println("Data:" + data);
        System.out.println("send port:" + port);
        // 4.關閉資源
        ds.close();
        /*
         * 運行結果:send IP:171.39.84.202 
         * Data:udp welcom to send 
         * port:8888
         */
    }
}</strong>

需求:鍵盤錄入數據發送到別的客戶端,輸入886停止發送

例子4:
發送端

<strong>public class UDPSent {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(8888);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while ((line = in.readLine()) != null) {
            if (line.equals("886"))
                break;
            byte[] buf = line.getBytes();
            DatagramPacket dp = new DatagramPacket(buf, buf.length,
                    InetAddress.getByName("171.39.84.202"), 10001);
            ds.send(dp);
        }
        ds.close();
    }
}</strong>


  需求: 接受發送方一直髮送的數據  ,不用關閉資源
 
例子5:
發送端

public class UDPReceive {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds = new DatagramSocket(10001);
        while (true) {
            byte[] buf = new byte[1024 * 64]; // 一個UDP數據包最大爲64kb
            DatagramPacket dp = new DatagramPacket(buf, buf.length);
            ds.receive(dp);
            String data = new String(dp.getData(), 0, dp.getLength());
            String address = dp.getAddress().getHostAddress();
            System.out.println(address + "-------" + data);
        }
    }
}


  需求:製作一個聊天工具

 編寫一個聊天程序
 有接受數據的部分和發送數據的部分
 這兩個部分需要同時執行
 那就需要用到多線程技術
 一個線程控制收,一個線程發

 因爲收和發動作是不一致的,所以要定義兩個run方法
 而且這兩個方法要封裝到不同的類中
 例子6:

public class ChatDemo {
    public static void main(String[] args) throws Exception {
        DatagramSocket send = new DatagramSocket(8880);
        DatagramSocket receive = new DatagramSocket(10003);
        new Thread(new Sent(send)).start();
        new Thread(new Receive(receive)).start();
    }
}
// 發送的線程
class Sent implements Runnable {
    private DatagramSocket ds;
    public Sent(DatagramSocket ds) {
        this.ds = ds;
    }
    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    System.in));
            String line = null;
            while ((line = in.readLine()) != null) {
                if ("886".equals(line))
                    break;
                byte[] buf = line.getBytes();
                DatagramPacket dp = new DatagramPacket(buf, buf.length,
                        InetAddress.getByName("171.39.84.255"), 10002);
                ds.send(dp);
            }
        } catch (Exception e) {
            new RuntimeException("發送端失敗");
        }
    }
}
// 接受線程
class Receive implements Runnable {
    private DatagramSocket ds;
    public Receive(DatagramSocket ds) {
        this.ds = ds;
    }
    @Override
    public void run() {
        try {
            while (true) {
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
 
                ds.receive(dp);
                String data = new String(dp.getData(), 0, dp.getLength());
                String address = dp.getAddress().getHostAddress();
                System.out.println(address + "---->" + data);
            }

        } catch (Exception e) {
            new RuntimeException("接收端失敗");
        }
    }
}

  演示:tcp傳輸。

 1.tcp分客戶端和服務端
 2、客戶端對應的對象是Socket
 服務端對應的對象是ServerSocket

 
 客戶端:
 通過查閱socket對象,發現在該對象建立時,就可以去連接指定主機
 因爲tcp是面向連接的,所以在建立socket服務時
 就要有服務端存在,並連接成功,形成通路後,在該通道進行數據傳輸

 步驟:
 1.創建Socket服務,並指定要連接的主句和端口
 例子7:
 

public class TcpClient {
    public static void main(String[] args) throws Exception {
        //創建客戶端的socket服務,指定目的主機和端口
        Socket s = new Socket("171.39.85.95", 10005);
        
        //爲了發送數據,應該獲取socket流中輸出流
        OutputStream in = s.getOutputStream();
        
        in.write("i am tcp".getBytes());
        
        s.close();
    }
}


 
 需求:定義端點接受數據並打印在控制檯上

 
服務端:

 1.建立服務端的socket服務,ServerSocket();
 並監聽一個端口
 2.獲取連接過來的客戶端對象
 通過ServerSocket的accept方法,沒有連接就會等,所以還這個方法阻塞試的
 
 3.客戶端如果發生過數據,那麼服務端要使用對應客戶端對象,並獲取到該客戶端的讀取流來讀取發過來的數據
 並打印在控制檯上
 
 4.關閉服務端(可選)
例子8: 
 
 

public class TcpServer {
    public static void main(String[] args) throws Exception {
        //建立服務端socket服務,並監聽一個端口
        ServerSocket ss = new ServerSocket(10005);
        
        //通過accept方法獲取連接過來的客戶端對象
        Socket s = ss.accept();
        
        //獲取客戶端發過來的數據,那麼要使用客戶端對象的讀取流來讀取數據
        InputStream in = s.getInputStream();
        
        byte[] by = new byte[1024];
        int len = in.read(by);
        String data = new String(by,0,len);
        
        InetAddress ia = s.getInetAddress();
        String ip = ia.getHostAddress();
        
        System.out.println(ip+"--->"+data);
        s.close();
    }
}

需求:
 建立一個文本轉換器服務器
 客戶端給服務端發送文本,服務端會將文本轉成大寫在返回給客戶端。
 而且客戶端可以不斷的進行文本轉換,當客戶端輸入over時,轉換結束。
 
 分析:
 客戶端:
 計入是操作設備上的數據,那麼就可以使用IO技術,並按照IO操作規律來思考、
 源:鍵盤錄入。
 目的:網路設備,網絡輸出流
 而且操作的是文本數據,可以選擇字符流
 
 步驟:
 1.建立服務
 2.獲取鍵盤錄入
 3.將數據發給服務端
 4.獲取服務端返回的大寫數據
 5.結束,關閉資源
 
 都是文本數據,可以使用字符流進行操作,通過提高效率,加入緩衝區
 該例子出現的問題:
 現象:客戶端和服務端都是在莫名的等待。
 爲什麼呢?
 因爲客戶端和服務端都有阻塞式 方法,這些方法沒有讀取到結束標記,那麼就一直等
 而導致兩端都在等待
例子9: 

class TransClient {
    public static void main(String[] args) throws Exception {
        // 創建客戶端的socket服務,指定目的主機和端口
        Socket s = new Socket("171.39.85.95",10009);
        //定義讀取鍵盤數據的流對象
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        //定義一個socket讀取流,讀取服務端返回的大寫信息
        BufferedReader bufin = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        //定義目的,將數據寫入到socket輸出流,發給客戶端
        BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(
                s.getOutputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
            if("over".equals(line))
                break;
            bufout.write(line);
            //一定要添加換行,不然服務端接受不到換行符,將會一直處於阻塞狀態
            bufout.newLine();    
            bufout.flush();
            String serverData = bufin.readLine();
            System.out.println(serverData);
        }
        s.close();
    }
}
class TransServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10009);
        Socket s = ss.accept();
        
        //獲取發送端的IP地址
        String clientIP = ss.getInetAddress().getHostAddress();
        System.out.println(clientIP+"......access");
        
        //讀取socket讀取流中的數據
        BufferedReader bufin = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        //目的,socket輸出流,將大寫數據寫入到socket輸出流中,併發送給客戶端
        BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(
                s.getOutputStream()));
        
        String line = null;
        while ((line = bufin.readLine()) != null) {
            System.out.println(line);
            bufout.write("server:"+line.toUpperCase());
            bufout.newLine();
            bufout.flush();
        }
        s.close();
        ss.close();
    }
}
 

 演示:tcp的傳輸的客戶端和服務端的互訪

需求:客戶端給服務端發送數據, 服務端收到後,給客戶端反饋信息
 客戶端:
 1.建立socket服務,指定要連接主機和端口
 2.獲取socket流中的輸出流,將數據寫到流中,通過網路發送給服務端
 3.獲取socket流中的輸入流,鍵服務端反饋的數據獲取到,並打印
 4.關閉客戶端資源
 例10:
class TcpClientDemo {
    public static void main(String[] args) throws Exception {
        // 創建客戶端的socket服務,指定目的主機和端口
        Socket s = new Socket("171.39.85.95", 10005);
        // 爲了發送數據,應該獲取socket流中輸出流
        OutputStream out = s.getOutputStream();
        out.write("i am tcp".getBytes());
        // 接受服務端發回的數據
        InputStream in = s.getInputStream();
        byte[] bt = new byte[1024];
        int len = in.read(bt);
        System.out.println(new String(bt, 0, len));
        s.close();
    }
}
class TcpServerDemo {
    public static void main(String[] args)throws Exception {
        // 建立服務端socket服務,並監聽一個端口
        ServerSocket ss = new ServerSocket(10005);
        // 通過accept方法獲取連接過來的客戶端對象
        Socket s = ss.accept();
        // 獲取客戶端發過來的數據,那麼要使用客戶端對象的讀取流來讀取數據
        InputStream in = s.getInputStream();
        byte[] by = new byte[1024];
        int len = in.read(by);
        String data = new String(by, 0, len);
        
        //返回給客戶端信息
        OutputStream out = s.getOutputStream();
        Thread.sleep(5000);
        out.write("服務端已經收到!!!!!".getBytes());
        
        InetAddress ia = s.getInetAddress();
        String ip = ia.getHostAddress();
        System.out.println(ip + "--->" + data);
        s.close();
        ss.close();
    }
}


 需求:將一個文本文件上傳到服務端

例子11:

<strong>//客戶端
class TextClient {
    public static void main(String[] args) throws Exception {
        // 創建客戶端的socket服務,指定目的主機和端口
        Socket s = new Socket("127.0.0.1", 10009);
        // 需要上傳的文件
        BufferedReader in = new BufferedReader(new FileReader(
                "FileReaderDemo_copyByBuf.txt"));
        // 網絡上傳傳輸流
        PrintWriter out = new PrintWriter(s.getOutputStream(), true);
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        s.shutdownOutput(); // 上傳的結束標記,關閉客戶端的輸出流,相當於給流中加入一個結束標記
        // 服務器返回數據
        BufferedReader server = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        String str = server.readLine();
        System.out.println("server:" + str);
        in.close();
        s.close();
    }
}
// 服務端
class TexServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10009);
        Socket s = ss.accept();
        // 獲取發送端的IP地址
        String clientIP = ss.getInetAddress().getHostAddress();
        System.out.println(clientIP + "......access");
        // 讀取socket讀取流中的數據
        BufferedReader bufin = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        PrintWriter pw = new PrintWriter(new FileWriter("server.java"), true);
        String line = null;
        while ((line = bufin.readLine()) != null) {
            pw.println(line);
        }
        // 目的,socket輸出流,將大寫數據寫入到socket輸出流中,併發送給客戶端
        PrintWriter client = new PrintWriter(s.getOutputStream(), true);
        client.println("上傳成功");
        s.close();
        ss.close();
    }
}</strong>

 需求:多用戶同時上傳圖片(重點)

 
服務端
這個服務端有個侷限性,當A客戶端連接上之後,被服務端獲取到,服務端執行具體流程
這時b客戶端連接,只有等待
因爲服務端還沒有處理玩A客戶端段的請求,還有循環回來執行下次accept方法 ,所以
暫時獲取不到B客戶端對象

那麼爲了可以讓多個用戶同時併發訪問服務端。
那麼服務端最好就是將每個客戶端封裝到一個單獨的線程中國,這樣就可以同時處理多個客戶端請求

如何定義線程呢?
只要明確了每一個客戶端要在服務端執行的代碼即可,將該代碼存入run方法中

例子12:
 
 輸入方式:java -jar PicClient.jar c:\\1.jpg

class PicClient {
    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.out.println("請選擇一個jpg格式的圖片");
            return;
        }
        File file = new File(args[0]);
        if (!(file.exists() && file.isFile())) {
            System.out.println("該文件有問題,要麼不存在,要麼不是文件");
            return;
        }
        if (!file.getName().endsWith(".jpg")) {
            System.out.println("圖片格式錯誤,請重新選擇");
            return;
        }
        if (file.length() > 1024 * 1024 * 8) {
            System.out.println("文件超過8M,不能上傳");
            return;
        }
        Socket s = new Socket("171.39.87.39", 10007);
        FileInputStream fis = new FileInputStream(file);
        OutputStream out = s.getOutputStream();
        byte[] by = new byte[1024];
        int len = 0;
        while ((len = fis.read(by)) != -1) {
            out.write(by, 0, len);
        }
        // 通知服務端數據已寫完
        s.shutdownOutput();
        InputStream in = s.getInputStream();
        byte[] bufIn = new byte[1024];
        int num = in.read(bufIn);
        System.out.println(new String(bufIn, 0, num));
        fis.close();
        s.close();
    }
}
class PicThread implements Runnable {
    private Socket s;
    PicThread(Socket s) {
        this.s = s;
    }
    @Override
    public void run() {
        // 獲取客戶端IP
        String ip = s.getInetAddress().getHostAddress();
        int count = 1;
        try {
            System.out.println(ip+".....conetion");
            File file = new File(ip + "(" + count + ").jpg");
            while(file.exists()) {
                file = new File(ip + "(" + (count++) + ").jpg");
            }
            InputStream in = s.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            OutputStream out = s.getOutputStream();
            out.write("上傳成功".getBytes());
            fos.close();
            s.close();
        } catch (Exception e) {
            throw new RuntimeException("線程上傳失敗!");
        }
    }
}
/*
服務端
 */
class PicServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10007);
        while (true) {
            Socket s = ss.accept();
            new Thread(new PicThread(s)).start();
        }
    }
}


 需求:多個用戶同時登入,服務端進行校驗
 
 客戶端通過鍵盤錄入用戶名
 服務端對這個用戶名勁翔校驗
 
 如果該用戶不存在,在服務端顯示xxx,已登入
 並在客戶端實現XXX,歡迎光臨
 
 如果該用戶不存在,在服務端顯示XXXX,嘗試登入
 並在客戶端顯示xxx,該用戶不存在
 
 最多登入三次
例子13: 

class LoginClient {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket("171.39.84.2", 10008);
        BufferedReader bufr = new BufferedReader(new InputStreamReader(
                System.in));
        BufferedReader in = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        for (int i = 0; i < 3; i++) {
            String line = bufr.readLine();
            if (line == null)
                break;
            out.println(line);
            
            String info = in.readLine();
            System.out.println("info:" + info);
            if (info.contains("歡迎"))
                break;
        }
        bufr.close();
        s.close();
    }
}
class UserThread implements Runnable {
    private Socket s;
    UserThread(Socket s) {
        this.s = s;
    }
    @Override
    public void run() {
        String IP = s.getInetAddress().getHostAddress();
        System.out.println(IP+"....connected");
        try {
            for (int i = 0; i < 3; i++) {
                BufferedReader bufr = new BufferedReader(new FileReader(
                        "user.txt"));
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        s.getInputStream()));
                
                String username = in.readLine();
                
                if(username == null)
                    break;
                PrintWriter out = new PrintWriter(s.getOutputStream(),true);
                
                String line = null;
                boolean flag = false;
                while((line = bufr.readLine()) != null){
                    if(line.equals(username)){
                        flag = true;
                        break;
                    }
                }
                
                if(flag){
                    out.println(username+"歡迎您");
                    System.out.println(IP+"::"+username+"::"+"用戶已登入");
                }else{
                    out.println("用戶不存在");
                }
            }
            
            s.close();
        } catch (Exception e) {
            throw new RuntimeException("檢驗失敗");
        }
    }
}
class LoginServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10008);
        while (true) {
            Socket s = ss.accept();
            new Thread(new UserThread(s)).start();
        }
    }
}


 
 需求:自定義一個客戶端,向Tomcat服務端發送請求
 
 自定義一個IE訪問服務端,並模擬瀏覽器向tomcat服務端發送必要的數據,
 
 tomcat服務器會將數據返回,我們要將數據打印在控制檯上
 返回的數據包括頭部和數據部分
例子14:

public class MyIE {
    public static void main(String[] args) throws  Exception {
        Socket s = new Socket("171.39.84.2",8080);
        
        PrintWriter out =  new PrintWriter(s.getOutputStream(),true);
        
        
        //模仿瀏覽器方式發送數據給TOmcat服務端
        out.println("GET /myweb/demo.html HTTP/1.1");
        out.println("Accept:*/*");
        out.println("Host: 171.39.84.2:11000");
        out.println("Cache-Control: max-age=0");
        out.println("Accept-Language: zh-CN,zh;q=0.8");
        out.println("Accept-Encoding: gzip,deflate,sdch");
        out.println("Connection: keep-alive");
        
        out.println();
        out.println();
        
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while((line=in.readLine()) != null){
            System.out.println(line);
        }
        s.close();
        
    }
}
/*
 * 
Tomcat服務端想客戶端發送回來的數據
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"156-1431832945631"
Last-Modified: Sun, 17 May 2015 03:22:25 GMT
Content-Type: text/html
Content-Length: 156
Date: Sun, 17 May 2015 03:22:33 GMT
<html>
<head>
<title>welcome to beijing </title>
</head>
<body>
<h>welcome to myweb</h>
<div >
jkfafelfsaljfdslfflemsfmek
</div>
</body>
*/

 演示:URL的基本常用方法 
 
String getFile() 
          獲取此 URL 的文件名。 
 String getHost() 
          獲取此 URL 的主機名(如果適用)。 
 String getPath() 
          獲取此 URL 的路徑部分。 
 int getPort() 
          獲取此 URL 的端口號。 
 String getProtocol() 
          獲取此 URL 的協議名稱。 
 String getQuery() 
          獲取此 URL 的查詢部分 
例子15: 

public class URlDemo {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://171.39.86.245:8080/myweb/demo.html?username=lisi");
        
        System.out.println("getProtocol() :" + url.getProtocol());
        System.out.println("getFile() :" + url.getFile());
        System.out.println("getHost() :" + url.getHost());
        System.out.println("getPath() :" + url.getPath());
        System.out.println("getQuery() :" + url.getQuery());
    }
}

 需求:使用瀏覽器訪問自定義的服務端

能直接通過瀏覽器直接訪問,只要輸入IP地址加服務端監聽的端口號10011
如:http://171.39.84.2:10011/
例子16:

public class ServerDemo {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10011);
        Socket s = ss.accept();
        
        System.out.println(s.getInetAddress().getHostAddress()+".......connected");
        
        
        InputStream in = s.getInputStream();
        byte[] bt = new byte[1024];
        int len = in.read(bt);
        System.out.println(new String(bt,0,len));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
//      out.println("<font color='red' size='3'>歡迎訪問服務端</font>");
        out.println("welcom to beijing ");
        s.close();
        ss.close();
    }
}
/*
 * 
瀏覽器客戶端想服務端發來的數據;
 GET / HTTP/1.1
Host: 171.39.84.2:10011
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8 
*/

  需求:自定義一個客戶端,向Tomcat服務端發送請求
 
 自定義一個IE訪問服務端,並模擬瀏覽器向tomcat服務端發送必要的數據,
 
 tomcat服務器會將數據返回,我們要將數據打印在控制檯上
 返回的數據包括頭部和數據部分
例子17: 

public class MyIE {
    public static void main(String[] args) throws  Exception {
        Socket s = new Socket("171.39.84.2",8080);
        
        PrintWriter out =  new PrintWriter(s.getOutputStream(),true);
        
        
        //模仿瀏覽器方式發送數據給TOmcat服務端
        out.println("GET /myweb/demo.html HTTP/1.1");
        out.println("Accept:*/*");
        out.println("Host: 171.39.84.2:11000");
        out.println("Cache-Control: max-age=0");
        out.println("Accept-Language: zh-CN,zh;q=0.8");
        out.println("Accept-Encoding: gzip,deflate,sdch");
        out.println("Connection: keep-alive");
        
        out.println();
        out.println();
        
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while((line=in.readLine()) != null){
            System.out.println(line);
        }
        s.close();
        
    }
}
/*
 * 
Tomcat服務端想客戶端發送回來的數據
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"156-1431832945631"
Last-Modified: Sun, 17 May 2015 03:22:25 GMT
Content-Type: text/html
Content-Length: 156
Date: Sun, 17 May 2015 03:22:33 GMT
<html>
<head>
<title>welcome to beijing </title>
</head>
<body>
<h>welcome to myweb</h>
<div >
jkfafelfsaljfdslfflemsfmek
</div>
</body>
*/
 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章