IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 【TCP-UDP通信学习(java)】 -> 正文阅读

[网络协议]【TCP-UDP通信学习(java)】

起初TCP基本通信

  • 服务端
public class SocketServer01 {
    public static void main(String[] args) throws IOException {
        //1. 在本机的9999端口监听,等待连接,要求本机的其他服务没有占用9999
        // ServerSocket可以通过accept()方法返回多个socket,即高并发
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端正在9999端口监听,等待连接...");
        //2. 当没有客户端连接9999端口时,程序会阻塞,等待连接
        //如果有客户端连接则会返回Socket对象,程序继续
        Socket accept = serverSocket.accept();
        System.out.println("服务端 socket返回 = " + accept.getClass());
        //3. 通过accept.getInputStream()读取数据显示
        InputStream inputStream = accept.getInputStream();
        //4. IO读取
        byte[] b = new byte[1024];
        int readLine = 0;
        while((readLine = inputStream.read(b)) != -1) {
            System.out.println(new String(b, 0, readLine));
        }
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("hello,client".getBytes(StandardCharsets.UTF_8));
        accept.shutdownOutput();
        inputStream.close();
        outputStream.close();
        accept.close();
        serverSocket.close();
    }
}
  • 客户端
public class SocketClient01 {
    public static void main(String[] args) throws IOException {
        //1. 连接服务端(ip,端口)
        //连接本机的9999端口,如果连接成功,返回Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("客户端 socket返回 = " + socket.getClass());
        //2. 连接上后生成socket,通过socket.getOutPutStream()
        // 得到和socket对象关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();
        //3. 通过输出流,写入数据到数据通道
        outputStream.write("hello,server".getBytes(StandardCharsets.UTF_8));
        //设置写入结束标记
        socket.shutdownOutput();
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int readLen = 0;
        while((readLen = inputStream.read(bytes)) != -1) {
            System.out.println(new String(bytes, 0, readLen));
        }
        //4. 关闭流对象和socket资源,必须关闭
        inputStream.close();
        outputStream.close();
        socket.close();
    }
}

UDP基本通信

  • 发送端
public class SenderUdp {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8889);
        byte[] data = "四大名著是哪些?".getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.80.1"), 8888);
        socket.send(packet);

        byte[] res = new byte[1024];
        packet = new DatagramPacket(res, res.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        socket.close();
    }
}
  • 接收端
public class ReceiveUdp {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);
        String res = new String(packet.getData(), 0, packet.getLength());
        System.out.println("收到了消息:" + res);
        if(res.equals("四大名著是哪些?")) {
            res = "<<红楼梦>,<>,<>,<>>";
        }
        else res = "what?";
        packet = new DatagramPacket(res.getBytes(StandardCharsets.UTF_8), res.getBytes(StandardCharsets.UTF_8).length, InetAddress.getByName("192.168.80.1"), 8889);
        socket.send(packet);
        socket.close();
    }
}

TCP双端通信简单聊天回复

  • 客户端
public class TcpClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //向服务器发送数据...
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while(loop){
            String info = scanner.next();
            if(info.equals("exit")) {
                loop = false;
            }
            bufferedWriter.write(info);
            bufferedWriter.newLine();
            bufferedWriter.flush();
            //======发送完毕
            System.out.println(bufferedReader.readLine());
        }

        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
    }
}

  • 服务器
public class TcpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);

        Socket socket = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

        boolean loop = true;
        while(loop){
            String s = bufferedReader.readLine();
            System.out.println("收到了来自客户端的消息:" + s);
            String res = "";
            if (s.equals("name")) {
                res = "我是nova";
            } else if(s.equals("hobby")){
                res = "编写java程序";
            }
            else if(s.equals("exit")) {
                res = "拜拜~";
                loop = false;
            }
            else {
                res = "你说啥呢";
            }
            bufferedWriter.write(res);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();
    }
}

TCP客户端上传文件到服务器

  • 客户端
public class TCPFileClient02 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        System.out.println("socket端口是:" + socket.getPort());
        String srcPath = "e:/background-pic/beau.jpg";
        FileInputStream fileInputStream = new FileInputStream(srcPath);
        System.out.println("读取图片的二进制数组...");
        byte[] bytesArray = FileUtils.getBytesArray(fileInputStream);
        System.out.println("字节数组长度为:" + bytesArray.length);
        //传输图片信息
        System.out.println("图片信息读取完毕...,向服务器传输图片...");
        OutputStream outputStream = socket.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        bos.write(bytesArray);
        socket.shutdownOutput();
        System.out.println("图片传输完成...");
        //接受服务端的信息
        InputStream inputStream = socket.getInputStream();
        System.out.println("等待服务器回复...");
        String info = FileUtils.getStringInfo(inputStream);
        System.out.println(info);
        System.out.println("完成,退出程序...");
        //关闭服务
        inputStream.close();
        fileInputStream.close();
        bos.close();
        socket.close();
    }
}

  • 服务器
public class TCPFileServer02 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务端正在8888端口监听...");
        Socket accept = serverSocket.accept();
        InputStream inputStream = accept.getInputStream();
        System.out.println("连接上了... 开始获取客户端输入...");

        byte[] res = FileUtils.getInfo(inputStream);
        System.out.println("字节数组长度为:" + res.length);
        System.out.println("客户端输入读取完毕...");

        OutputStream outputStream = accept.getOutputStream();
        String dstPath = "e:/background-pic/server.jpg";
        System.out.println("开始保存图片文件...");
        FileUtils.writeJpgToFile(res, dstPath);
        System.out.println("保存完成...");

        System.out.println("向客户端传输保存完成的消息...");
        FileUtils.transportInfo("I get it", outputStream);
        accept.shutdownOutput();
        System.out.println("整个过程任务结束...退出程序...");
        //全部关闭
        outputStream.close();
        inputStream.close();
        accept.close();
        serverSocket.close();
    }
}
  • FileUtils工具类
public class FileUtils {
    //获取文件的二进制信息
    public static byte[] getBytesArray(InputStream inputStream) throws IOException {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] bt = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int readLen = 0;
        while((readLen = bufferedInputStream.read(bt)) != -1) {
            bos.write(bt, 0 , readLen);
        }
        //关闭流
        byte[] array = bos.toByteArray();
        bufferedInputStream.close();
        bos.close();
        return array;
    }
    public static byte[] getInfo(InputStream inputStream) throws IOException {
        int readLen = 0;
        byte[] bt = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((readLen = inputStream.read(bt)) != -1) {
            bos.write(bt, 0, readLen);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return array;
    }
    public static String getStringInfo(InputStream inputStream) throws IOException {
        int readLen = 0;
        byte[] bt = new byte[1024];
        String res = "";
        while((readLen = inputStream.read(bt)) != -1) {
            res += new String(bt, 0, readLen);
        }
        return res;
    }
    public static void writeJpgToFile(byte[] res, String dstPath) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(dstPath);
        BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
        bos.write(res);
        //关闭流
        bos.flush();
        bos.close();
    }
    public static void transportInfo(String info, OutputStream os) throws IOException {
        os.write(info.getBytes());
    }
}

客户端从服务器下载文件

  • 客户端
public class ClientSocket {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        OutputStream outputStream = socket.getOutputStream();
        InputStream inputStream = socket.getInputStream();

        System.out.println("请输入你要下载的文件名:");
        Scanner scanner = new Scanner(System.in);
        String fileName = scanner.next();
        System.out.println("向服务器传输要下载的文件名...");
        outputStream.write(fileName.getBytes());
        socket.shutdownOutput();
        System.out.println("已告知服务器要下载的文件名...");

        System.out.println("等待下载文件中...");
        byte[] bytesArray = FileUtils.getBytesArray(inputStream);
        System.out.println("已经下载到了文件...开始保存到本地");
        String dstPath = "E:\\background-pic\\res\\123.jpg";
        FileUtils.writeJpgToFile(bytesArray, dstPath);
        System.out.println("保存完成,请在对应的目录下查看,即将退出...");
        scanner.close();
        inputStream.close();
        outputStream.close();
        socket.close();
    }
}
  • 服务器
public class ServerSocket0 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("8888端口等待客户端连接...");
        Socket socket = serverSocket.accept();
        OutputStream outputStream = socket.getOutputStream();
        InputStream inputStream = socket.getInputStream();
        //先读取要下载的文件名
        System.out.println("已连接...正在从客户端获取需要下载的文件名...");
        byte[] info = FileUtils.getInfo(inputStream);
        String fileName = new String(info);
        System.out.println("需要下载的文件名为:" + fileName);
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        if (file.exists()) {
            fileInputStream = new FileInputStream(fileName);
            System.out.println("需要下载的文件存在...");
        }
        else {
            fileInputStream = new FileInputStream("e:/background-pic/beau.jpg");
            System.out.println("需要下载的文件不存在...即将为您下载默认的jpg文件");
        }
        System.out.println("开始读取数据库中的文件...");
        byte[] bytesArray = FileUtils.getBytesArray(fileInputStream);
        System.out.println("读取完毕,开始传输给客户端...");
        outputStream.write(bytesArray);
        socket.shutdownOutput();
        System.out.println("传输完毕,服务器即将关闭...");
        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }
}

结束~~撒花,常复习~

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-03-30 19:06:09  更:2022-03-30 19:06:24 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 5:58:03-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码