网络原理大概 这里 没有填写,后期会补

TCP

server端

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

public class TCPServer {

    public static void main(String[] args) throws IOException {
        try {
            //创建服务器的Socket对象
            ServerSocket serverSocket = new ServerSocket(8899);
            System.out.println("服务器启动");
            //创建监听对象(包含网络传输的内容)
            Socket accept = serverSocket.accept();
            //使用流 方便下面获取
            InputStream inputStream = accept.getInputStream();
            byte[] bytes = new byte[1024];
            int length = inputStream.read(bytes);
            System.out.println(new String(bytes, 0, length));
            //inputStream.close();  //serverSocket对象close,inputStream就不需要close();
            serverSocket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

client端

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


public class TCPClient {

public static void main(String[] args) throws IOException {
try {
//创建Socket对象 并指定服务器IP,端口
Socket socket = new Socket("127.0.0.1",8899);
//获取流写数据
OutputStream os = socket.getOutputStream();
//写数据
os.write("AaBb123你好".getBytes());
//释放资源
//os.close(); //因为os是通过socket获取的,关闭socket即可
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}

UDP

client端

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive {
    public static void main(String[] args){
        //创建Socrkt 指定端口 DatagramSocket
        try {

            //创建数据包 创建参数
            while (true){
                //创建DatagramSocket对象,指定监听端口10086
                DatagramSocket ds = new DatagramSocket(10086);
                byte[] bys = new byte[1024];
                //创建DatagramPacket对象,将来接收包数据
                DatagramPacket dp = new DatagramPacket(bys,bys.length);
                //用创建DatagramSocket对象 接收 创建DatagramPacket对象
                ds.receive(dp);
                //从创建DatagramPacket对象 获取数据
                bys = dp.getData();
                //输出数据
                System.out.println(new String(bys, 0, dp.getLength()));
                //关闭对象
                ds.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

server端

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

public class UDPSend {
    public static void main(String[] args) throws IOException {
        //创建Socrkt DatagramSocket
        DatagramSocket ds = new DatagramSocket();
        //创建数据包 创建参数
        int port = 10086;
        byte[] bys = "AaBb123你好".getBytes();
        int length = bys.length;
        InetAddress ipv4 = InetAddress.getByName("127.0.0.1");
        //创建一个数据包DatagramPacket
        DatagramPacket dp = new DatagramPacket(bys, length, ipv4, port);
        //发送数据
        ds.send(dp);
        //关闭DatagramSocket对象
        ds.close();
    }
}