Implementation of TCP connection establishment and UDP connection establishment in Java network programming

How TCP establishes a connection

<When you click Run, you need to run the server first, and then run the client. (Reason: When TCP establishes a connection, it will handshake, if there is no response, the connection will fail)

package NetWorkPrograming;

import org.junit.Test;

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

/**
 * @Author:CT
 * @Date:2021/2/16
 * @Description:NetWorkPrograming
 * @Version 1.0
 */
/*
   一: 网络通信协议:
    ① TCP协议  建立连接需要三次握手,四次挥手


    ② UDP协议 建立连接无需建立连接 但是会丢包
 */
public class NetWorkPrograming02 {
    
    
    // 客户端
    @Test
    public void test(){
    
    
        // 1.创建Socket对象:指明服务器端的IP 和端口号
        Socket socket= null;
        // 2. 获取输出流去写出数据
        OutputStream outputStream = null;
        try {
    
    
            InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inetAddress,8899);
            outputStream = socket.getOutputStream();
            outputStream.write("你好,我是客户端".getBytes());
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    

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



    }
    // 服务器
    @Test
    public void test1(){
    
    
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        try {
    
    
            //1. 创建服务器端的Socket 指明自己的端口号
            serverSocket = new ServerSocket(8899);
            //2. 调用accept() 方法表示可以接受来自客户端的Socket
            accept = serverSocket.accept();
            //3. 获取输入流
            inputStream = accept.getInputStream();
            //4. 读取输入流的数据
            //方式一:此写法会造成乱码的可能 因为一个中文在UTF-8 编码当中占3个字节 可能会遇见把一个字分为两半的情况,就会造成乱码

//            byte[]bytes=new byte[1024];
//            int len;
//            while ((len=inputStream.read(bytes))!=-1){
    
    
//                String s=new String(bytes,0,len);
//                System.out.println(s);
//            }

            // 方式二: 解决乱码的方式
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes=new byte[5];//此处可以不用管new了几个字符进去 此类会自动填补 不会把字分为两半
            int len;
            while ((len=inputStream.read(bytes))!=-1){
    
    
                byteArrayOutputStream.write(bytes,0,len);

            }
            System.out.println(byteArrayOutputStream.toString());
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                if (serverSocket!=null){
    
    
                    serverSocket.close();
                }

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

            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }


    }
}

UDP connection establishment
<When the UDP connection is started, the receiving end needs to be started first, otherwise it will fall into infinite waiting (because the receiving end is started later, the sending end will have sent the data, and the receiving end has been waiting)

package NetWorkPrograming;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Author:CT
 * @Date:2021/2/16
 * @Description:NetWorkPrograming
 * @Version 1.0
 */
/*
    UDP的连接操作
 */
public class UDP {
    
    
    // 发送端
    @Test
    public  void  test(){
    
    
        // 建立数据传输的
        DatagramSocket datagramSocket = null;
        try {
    
    
            datagramSocket = new DatagramSocket();
            // 用来存放数据
            String s="你好";
            byte[] bytes=s.getBytes();
            InetAddress inetAddress=InetAddress.getLocalHost();
            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,inetAddress,8099);

            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            datagramSocket.close();
        }

    }
    @Test
    // 接收端
    public void  test1(){
    
    
        DatagramSocket datagramSocket = null;
        try {
    
    
            datagramSocket = new DatagramSocket(8099);
            byte[]bytes=new byte[100];
            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
            datagramSocket.receive(datagramPacket);
            System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            datagramSocket.close();
        }

    }

}

Guess you like

Origin blog.csdn.net/weixin_46351306/article/details/113830034