1. 程式人生 > 其它 >Java-網路程式設計程式碼

Java-網路程式設計程式碼

InetAddress關鍵字

為了方便我們獲取和操作IP地址,java提供了一個類InetAddress 供我們使用
  • 確定主機名稱的IP地址。public static InetAddress getByName(String host)
  • 獲取此IP地址的主機名。String getHostName()
  • 返回文字顯示中的IP地址字串,String getHostAddress()。
程式碼如下:
public class InetAddressDemo {
    public static void main(String[] args) {
        //public static InetAddress getByName(String host) throws UnknownHostException
        // 確定主機名稱的IP地址。
        InetAddress addressName = null;
        try {
            addressName = InetAddress.getByName("192.168.10.147");
            System.out.println(addressName);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //String getHostName()
        //獲取此IP地址的主機名。
        String hostName = addressName.getHostName();
        System.out.println(hostName);

        //String getHostAddress()
        //返回文字顯示中的IP地址字串。
        String hostAddress = addressName.getHostAddress();
        System.out.println(hostAddress);

        //static InetAddress getLocalHost()
        //返回本地主機的地址。
        try {
            InetAddress localHost = addressName.getLocalHost();
            System.out.println(localHost);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

UDP 協議建立連線

UDP協議傳送資料的步驟:

  • 1.建立傳送端的Socket物件
  • 2.建立資料,並將資料打包
  • 3.呼叫Socket物件中的一個辦法,將資料包傳送出去
  • 4.釋放資源,關閉Socket物件
public class SendDemo1 {
    public static void main(String[] args) {
        //建立傳送端的Socket物件
        //DatagramSocket()
        //構造資料報套接字並將其繫結到本地主機上的任何可用埠。
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        //將資料轉成位元組陣列
        byte[] bytes = "雲想衣裳花想容".getBytes();
        //獲取位元組陣列的長度
        int len = bytes.length;
        //IP地址,(你要傳送給誰的ip地址)
        InetAddress address = null;
        try {
            address = InetAddress.getByName("192.168.10.147");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //指定接收的資料埠
        int port = 10086;

        //建立一個數據包
        //DatagramPacket(byte[] buf, int length, InetAddress address, int port)
        //構造用於傳送長度的分組的資料報包 length指定主機上到指定的埠號。
        DatagramPacket datagramPacket = new DatagramPacket(bytes, len, address, port);

        //void send(DatagramPacket p)
        //從此套接字傳送資料報包。
        try {
            ds.send(datagramPacket);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //釋放資源,關閉Socket物件
        ds.close();
    }
}

UDP接收端程式碼步驟

  • 1.接收端的Socket物件
  • 2.建立一個數據包(用來接收資料的容器)
  • 3.呼叫Socket物件中的方法來接收資料
  • 4.解析資料包,列印在控制檯上
  • 5.釋放資源
  • 注意:接收端不能重複啟動
public class ReceiveDemo1 {
    public static void main(String[] args) {
        //建立接收端的Socket物件
        //DatagramSocket(int port)
        //建構函式報套接字並將其繫結到本地主機的指定埠
        DatagramSocket ds = null;
        try {
          ds= new DatagramSocket(10086);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        //建立一個數據包(用來接收資料的容器)
        //DatagramPacket(byte[] buf,int length)
        //構造一個 DatagramPacket 用於接收資料包length
        byte[] bytes = new byte[1024];
        int len = bytes.length;
        DatagramPacket dp = new DatagramPacket(bytes, len);

        //呼叫Socket物件中的方法來接收資料
        //void receive(DatagramPacket P)
        try {
            ds.receive(dp); // 阻塞方法
        } catch (IOException e) {
            e.printStackTrace();
        }
         InetAddress address = dp.getAddress();
        String ip = address.getHostAddress();
        String hostName = address.getHostName();

        //解析資料包,列印到控制檯上
        //byte[] getData()
        //返回資料緩衝區
        byte[] data = dp.getData();
        int length = dp.getLength();//獲取實際長度
        String s = new String(data,0,length);
        System.out.println(hostName+",IP地址為:"+ip+"傳送的內容為:"+s);

        //釋放資源
        ds.close();
    }
}

通過迴圈改進,程式碼如下

傳送端:

package com.bigdat.java.day28.udpcoding;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class SendDemo2 {
    public static void main(String[] args) {

        while(true){
            DatagramSocket ds = null;
            //傳送端傳送資料
            try {
                ds = new DatagramSocket();
            } catch (SocketException e) {
                e.printStackTrace();
            }
            //建立一個輸入物件
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            if("886".equals(next)){
                break;
            }else{
                byte[] bytes = next.getBytes();
                int length = bytes.length;
                InetAddress address = null;
                try {
                    address = InetAddress.getByName("192.168.10.147");
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                int port = 10086;

                DatagramPacket datagramPacket = new DatagramPacket(bytes,length,address,port);

                try {
                    ds.send(datagramPacket);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //關閉資源
                //ds.close();
            }

        }
    }
}

接收端:

package com.bigdat.java.day28.udpcoding;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class ReceiveDemo2 {
    public static void main(String[] args) {
        //建立接收物件
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(10086);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        System.out.println("====================接收端開始接收資料:=======================");
        while(true){
            //建立一個DatagramPacket 類的物件建立一個容器
            byte[] bytes = new byte[1024];
            int length = bytes.length;
            DatagramPacket dp = new DatagramPacket(bytes,length );

            //呼叫Socket方法receive 方法接收資料
            try {
                ds.receive(dp); // 阻塞資料包
            } catch (IOException e) {
                e.printStackTrace();
            }
            InetAddress address = dp.getAddress();
            String hostName = address.getHostName(); //IP地址對應主機名
            String hostAddress = address.getHostAddress();//IP 地址

            byte[] data = dp.getData();
            int length1 = data.length;
            String s = new String(data, 0, length1);
            System.out.println(hostName+",IP地址為:"+hostAddress+"傳送的資訊為:"+s);

        }
    }
}

TCP協議建立連線

TCP協議傳送資料的步驟:

  • 1.建立客戶端的Socket物件
    這一步一旦成功就證明連線成功
  • 2.獲取通道中的輸出流物件,寫資料
  • 3.釋放資源

客戶端程式碼

public class ClientDemo1 {
    public static void main(String[] args) throws Exception {
        //此構造方法較為繁瑣,一般不用
        //Socket(InetAddress address, int port)
        //建立流套接字並將其連線到指定IP地址的指定埠號。
        //Socket socket = new Socket(InetAddress.getByName("192.168.10.147\""),10086);

        //Socket(String host, int port)
        //建立流套接字並將其連線到指定的主機上的指定埠
        Socket socket = new Socket("192.168.10.147", 10086);

        //獲取通道中的輸出流物件,寫資料
        while(true){
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            if("886".equals(next)){
                break;
            }else{
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(next.getBytes());
            }

        }
        //釋放資源
        socket.close();
    }
}

伺服器端程式碼:

public class ClientDemo1 {
    public static void main(String[] args) throws Exception {
        //此構造方法較為繁瑣,一般不用
        //Socket(InetAddress address, int port)
        //建立流套接字並將其連線到指定IP地址的指定埠號。
        //Socket socket = new Socket(InetAddress.getByName("192.168.10.147\""),10086);

        //Socket(String host, int port)
        //建立流套接字並將其連線到指定的主機上的指定埠
        Socket socket = new Socket("192.168.10.147", 10086);

        //獲取通道中的輸出流物件,寫資料
        while(true){
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            if("886".equals(next)){
                break;
            }else{
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(next.getBytes());
            }

        }
        //釋放資源
        socket.close();
    }
}

改進(客戶端傳送資料後,伺服器端有返回值)

客戶端

package com.bigdat.java.day28.tcpcoding;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientDemo2 {
    public static void main(String[] args) {
        Socket socket = null;
        try {
            socket = new Socket("192.168.10.147",19999 );
        } catch (IOException e) {
            e.printStackTrace();
        }

        while(true){
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            if("886".equals(next)){
                System.out.println("連線已斷開...");
                break;
            }else{
                OutputStream outputStream = null;
                InputStream inputStream = null;
                try {
                    outputStream = socket.getOutputStream();
                    inputStream = socket.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    outputStream.write(next.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] bytes = new byte[1024];
                int length = 0;
                try {
                   length = inputStream.read(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String s = new String(bytes, 0, length);
                System.out.println("伺服器返回的訊息是:"+s);

            }
        }
    }
}

伺服器端

package com.bigdat.java.day28.tcpcoding;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo2 {
    public static void main(String[] args) {
        ServerSocket sSocket = null;
        try {
            sSocket = new ServerSocket(19999);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Socket accept = null;
        try {
            accept = sSocket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(true){
            OutputStream outputStream = null;
            InputStream inputStream = null;
            try {
                outputStream = accept.getOutputStream();
                inputStream = accept.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            byte[] bytes = new byte[1024];
            int len =0;
            try {
               len = inputStream.read(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String s = new String(bytes, 0, len);

            InetAddress inetAddress = accept.getInetAddress();
            String hostName = inetAddress.getHostName();
            String hostAddress = inetAddress.getHostAddress();
            System.out.println(hostName+",IP地址為:"+hostAddress+"客戶端上傳的資訊是:"+s);

            try {
                outputStream.write("伺服器端已經接收到!!!".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}