天天看點

網絡程式設計中TCP/UDP程式設計的執行個體

劍指Offer 16

操作給定的二叉樹,将其變換為源二叉樹的鏡像。

public class Offer18 {
    public void solution(TreeNode root){
        if (root==null){
            return;
        }

        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        solution(root.left);
        solution(root.right);

    }
}
           

socket程式設計示例

TCP(傳輸控制協定)概述

  • TCP面向連接配接的協定
  • TCP連接配接有兩端(點對點的通信)
  • TCP提供可靠的傳輸服務
  • 傳輸完畢,徐世芳已建立的連接配接,效率比UDP低

    1.利用tcpt進行字元傳遞,并顯示在控制台中

    用戶端

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

//用戶端
public class ClientTest {

    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            //建立tcp連接配接
            InetAddress inet = InetAddress.getByName("192.168.246.1");
            socket = new Socket(inet, 8989);
            //socket輸出流
            outputStream = socket.getOutputStream();
            outputStream.write("我最帥,我最帥".getBytes());

            //關閉資源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }
}

           

服務端

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服務端
public class ServerTest {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket socket =null;

        ByteArrayOutputStream baos=null;
        try{
            //serversocket擷取連結
            ss = new ServerSocket(8989);
            socket = ss.accept();
            //scoket輸入流
            InputStream is = socket.getInputStream();
            baos = new ByteArrayOutputStream();

            //寫入
            byte[] buffer = new byte[1024*1024];
            int len;
            while ((len = is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(socket.getInetAddress().getHostAddress());
            //擷取用戶端的ip位址
            System.out.println(baos.toString());
            //釋放資源
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }
}

           

2、在tcp程式設計中傳遞檔案

用戶端

public class ClientTest {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),1111);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("C:\\Users\\Administrator\\IdeaProjects\\springboot\\27-java-review\\1.png"));
        byte[] bytes = new byte[1024];
        int len;
        while ((len=fis.read(bytes))!=-1){
            os.write(bytes,0,len);
        }
        socket.shutdownOutput();

        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes1 = new byte[20];
        int len1;
        while ((len1=is.read(bytes1))!=-1){
            baos.write(bytes1,0,len1);
        }
        System.out.println(baos.toString());


        fis.close();
        os.close();
        socket.close();
    }
}

           

服務端

public class ServerTest {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(1111);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("4.png"));
        byte[] bytes = new byte[1024];
        int len;
        while ((len=is.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }
        System.out.println("接受完成");

        OutputStream os = socket.getOutputStream();
        os.write("我已收到檔案".getBytes());



        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}

           

UDP程式設計示例

UDP(使用者資料報協定)概述

  • UDP是無連接配接的協定
  • UDP不能保證可靠的傳遞資料
  • UDP是面向封包傳輸的
  • 傳輸完畢,無需釋放資源,開銷小,相對于TCP效率快

    發送端

public class Send {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();

        String str = "以UDP的方式發送資料";
        byte[] data = str.getBytes();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,InetAddress.getLocalHost(),1111);
        socket.send(packet);
        socket.close();

    }
}

           

接收端

public class Receive {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(1111);

        byte[] bytes = new byte[100];

        DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
        socket.receive(packet);


        System.out.println(new String(packet.getData(),0,packet.getLength()));
        socket.close();

    }
}