網絡(Socket)編程

網絡編程:就是在網絡上按照通信協議(TCP/UDP)傳輸數據,也就是說網絡編程是建立在IO流與通信協議之上的,之前我已經學了IO流
我這裏只記根據通信協議下的網絡編程,即TCP和UDP,還有一個URL的通信,至於通信需要IP地址+端口號這類網絡基礎知識,我就不囉嗦了,遇到具體問題具體分析,先掌握大致的方法(通過自己寫的例子來理解TCP/UDP的意義)
TCP舉例:

package com.ligang.www;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import org.junit.Test;

public class TcpTest {
    /*1.創建一個socket,指明服務器的IP地址和端口號
     * 2.發送數據,並返回一個輸出流
     * 3.發送什麼
     * 4.發送
     * 5.告訴服務器我已經發送完畢
     * 6.接收來自服務端的數據並將它們輸出到終端
     * 7.從下往上關閉文件流
     */
    @Test
    public void cliver(){
        Socket ss = null;
        OutputStream ee = null;
        Scanner dd = null;
        InputStream bb = null;
        try {
            ss = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
            ee = ss.getOutputStream();
            System.out.println("請輸入字符串:");
            dd = new Scanner(System.in);
            String str=dd.next();
            ee.write(str.getBytes());
            ss.shutdownOutput();
            bb = ss.getInputStream();
            byte [] b=new byte[10];
            int len;
            while((len=bb.read(b))!=-1){
                String str2=new String(b, 0, len);
                System.out.println(str2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            if(bb!=null){
                try {
                    bb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(dd!=null){
                dd.close();
            }
            if(ee!=null){
                try {
                    ee.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void sever(){
        /*1.創建一個ServerSocket的對象,通過構造器指明自身的端口
            2.調用其accept()方法,返回一個Socket的對象
            3.調用Socket對象的getInputStream()獲取一個從客戶端發送過來的輸入流
            4.對獲取的輸入流進行的操作,將其轉換成大寫
            5.調用Socket對象的getOutputStream()獲取一個向服務器法搜數據的輸出流
            6.將轉換後的字符串發送給客戶端
            7.依次關閉文件流
         */
        ServerSocket ss = null;
        Socket e = null;
        InputStream ee = null;
        OutputStream r = null;
        try {
            ss = new ServerSocket(9090);
            e = ss.accept();
            ee = e.getInputStream();
            byte [] b=new byte[10];
            int len ;
            String str=new String();
            while((len=ee.read(b))!=-1){
                String str1=new String(b, 0, len);
                str=str1+str;
            }
            String str3=str.toUpperCase();
            r = e.getOutputStream();
            r.write(str3.getBytes());
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally {
            if(r!=null){
                try {
                    r.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(ee!=null){
                try {
                    ee.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(e!=null){
                try {
                    e.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


}

UDP舉例:

package com.ligang.www;

import java.io.*;
import java.net.*;

import org.junit.Test;

/*
 * UDP數據報通過數據報套接字 DatagramSocket 發送和接收
 * DatagramPacket 對象封裝了UDP數據報,
 * 在數據報中包含了發送端的IP地址和端口號以及接收端的IP地址和端口號
 */
public class UdpTest {
    @Test
    public void send(){//發送端
        DatagramSocket ds=null;
        try {
            ds = new DatagramSocket();//定義一個udp的socket接口負責發送數據
            byte b[]="你好 ,我來看你來了".getBytes();//定義一個發送數據的數組
            DatagramPacket fs=new DatagramPacket(b,0,b.length,
                    InetAddress.getByName("127.0.0.1"), 9875);//定義一個udp的socket包,負責數據傳輸
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(ds!=null){
                ds.close();//關閉socket接口
            }
        }
    }
    @Test
    public void revice(){//接收端
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(9875);//在接收端接收來自發送端的接口
            byte [] b=new byte [1024];//定義一個數組專門做接收的容器
            DatagramPacket fs = new DatagramPacket(b, 0, b.length);
            ds.receive(fs);//定義一個udp的包來接收發送端的數據包
            String str =new String(fs.getData(), 0, fs.getLength());//將接受到的數據包轉化成字符串的形式以便輸出
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(ds!=null){
                ds.close();//關閉
            }
        }
    }

}

URL舉例:

package com.ligang.www;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.junit.Test;

public class UrlTest {
    @Test
    public void Url(){
        InputStream is =  null;
        InputStream is2=  null;
        FileOutputStream fos=null;
        try {
            URL url =new URL("http://127.0.0.1:8080/examples/javac---.txt");//先建立一條指定的鏈接
            URLConnection url1 = url.openConnection();//這個類既可以從網絡上讀數據,也可以發數據
            is = url.openStream();//這個類僅僅能從網絡上讀取數據,不能將數據發送回去
            is2=url1.getInputStream();//從網絡上讀取數據
            fos=new FileOutputStream(new File("178.txt"));//建立一個文件來存儲將要從服務器下載下來數據
            byte [] b=new byte[10];
            int len;
            while((len=is.read(b))!=-1){//將從服務器獲取到的數據輸出到終端上
                String str=new String(b, 0, len);
                System.out.print(str);
            }
            while ((len=is2.read(b))!=-1){//將從服務器獲取到的數據輸出到文件中
                fos.write(b, 0, len);
            }
        } 
         catch (IOException e) {
            e.printStackTrace();
        }finally{//從前往後依次關閉文件流
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            }
            if (is2!=null) {
                try {
                    is2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

註釋:上面的例子 中拋了好多的異常,那是系統自己拋的 我們只要捕獲就行,IO和Socket接口資源是非常珍貴的系統資源,一定要記得關閉

發佈了40 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章