网络编程

TCP网络编程

1、TCP发送数据

客户端

package com.dzxy.lesson02;

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

/**
 * @author job knight
 * @date 2020/8/20 -16:21
 */
public class TcpClientDemo02 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        Scanner sc = new Scanner(System.in);

        try {
            //获取IP地址和端口号
            InetAddress address = InetAddress.getByName("127.0.0.1");
            int post = 9090;
            //创建socket连接
            socket = new Socket(address, post);
            //获取输出流
            os = socket.getOutputStream();
            String msg = sc.nextLine();
            //写入数据
            os.write(msg.getBytes());

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

服务器端

package com.dzxy.lesson02;

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

/**
 * @author job knight
 * @date 2020/8/20 -16:34
 * 不停接受数据,不过连接一次接受一次,数据刷新一次
 */
public class TcpServerDemo02 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        byte[] buffer = new byte[1024];
        int len;
        while (true) {
            try {
                serverSocket = new ServerSocket(9090);
                socket = serverSocket.accept();
                is = socket.getInputStream();
                baos = new ByteArrayOutputStream();

                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

2、文件传输

客户端

package com.dzxy.lesson02;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author job knight
 * @date 2020/8/21 -17:50
 */
public class TcpClientDemo03 {
    public static void main(String[] args) throws IOException {
        //1、找到连接的地址和端口
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
        //2、获得数据流
        OutputStream os = socket.getOutputStream();
        //3、获得文件输入流
        File file = new File("S70817-102429.jpg");
        FileInputStream fis = new FileInputStream(file);
        //4、缓冲区设置
        byte[] buffer = new byte[1024];
        int len;
        //5、套接
        while ((len=fis.read(buffer))!= -1){
            os.write(buffer,0,len);
        }
        //6、完成传输
        socket.shutdownOutput();
        //7、关闭连接
        if (fis!=null){
            fis.close();
        }
        if (os!=null){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket!=null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

服务器端

package com.dzxy.lesson02;

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

/**
 * @author job knight
 * @date 2020/8/21 -17:51
 */
public class TcpServerDemo03 {
    public static void main(String[] args) throws IOException {
        //1、设置端口号ServerSocket
        ServerSocket serverSocket = new ServerSocket(9090);
        //2、连接上之后的到socket
        Socket socket = serverSocket.accept();
        //3、获取输入流
        InputStream is = socket.getInputStream();
        //4、文件输出地址
        File file = new File("copy.jpg");
        FileOutputStream fos = new FileOutputStream(file);
        //5、缓冲区
        byte[] buffer = new byte[1024];
        int len;
        //6、套接
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer);
        }
        //7、关闭连接
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

UDP网络编程

1、发送数据包(一发一收)

发送方

package com.dzxy.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author job knight
 * @date 2020/8/21 -21:53
 */
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1、传输连接对象
        InetAddress address = InetAddress.getByName("127.0.0.1");
        DatagramSocket socket = new DatagramSocket();
        //2、建包
        String msg = "你好";
        byte[] msgBytes = msg.getBytes();
        DatagramPacket packet = new DatagramPacket(msgBytes, msgBytes.length,address,9090);
        //3、传包
        socket.send(packet);
        //4、关闭连接
        socket.close();
    }
}

接收方

package com.dzxy.lesson03;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author job knight
 * @date 2020/8/21 -21:53
 */
public class UdpServerDemo01 {
    public static void main(String[] args) throws IOException {
        //1、接受连接
        DatagramSocket socket = new DatagramSocket(9090);
        //2、创建数据包
        byte[] buffer = new byte[1024];
        int len;
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        //3、接收存放数据包
        socket.receive(packet);
        byte[] data = packet.getData();
        System.out.println(new String(data));
        //4、关闭连接
        socket.close();
    }
}

2、循环发送数据

发送端

package com.dzxy.Chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author job knight
 * @date 2020/8/22 -15:42
 */
public class UdpSenderDemo01 {
    public static void main(String[] args) throws IOException {
        //1、新建datagramsocket
        InetAddress address = InetAddress.getByName("127.0.0.1");
        int psot = 6060;
        String msg = null;
        DatagramSocket socket = new DatagramSocket(9090);
        //3、输入数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            msg = reader.readLine();
            //4、数据包打包
            DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,address,psot);
            //5、数据包发送
            socket.send(packet);
            if ("bye".equals(msg)){
                break;
            }
            msg = null;
        }

        //6、关闭流
        socket.close();
    }
}

接收方

package com.dzxy.Chat;

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

/**
 * @author job knight
 * @date 2020/8/22 -15:42
 */
public class UdpReceiverDemo01 {

    public static void main(String[] args) throws IOException {
        byte[] buffer = new byte[1024];
        int len;
        byte[] data =null;
        DatagramPacket packet = null;
                //1、获取datagramsocket对象,设置端口,地址
        DatagramSocket socket = new DatagramSocket(6060);
        InetAddress address = InetAddress.getByName("127.0.0.1");
        //2、缓冲区设置

        //3、数据包建立

        //4、包接收并输出
        while (true){
            packet = new DatagramPacket(buffer, 0, buffer.length);
            socket.receive(packet);
            data = packet.getData();
            String msg = new String(data, 0, data.length);
            System.out.println(msg);
            buffer = new byte[1024];
            data = null;
            if ("bye".equals(msg)){
                break;
            }
        }
        //5、关闭连接
        socket.close();
    }
}

Bug

上面的一版解决了老师写的缓存不能覆盖存在遗留缓存的现象,但是还存在接收端不能结束socket的问题

原文地址:https://www.cnblogs.com/yuknight/p/13740785.html