【Java】网络编程-UDP回响服务器客户端简单代码编写

news/2024/5/18 14:26:21 标签: 网络, udp, 服务器, java

这一篇文章我们将讲述网络编程中UDP服务器客户端的编程代码

1、前置知识

UDP协议全称是用户数据报协议,在网络中它与TCP协议一样用于处理数据包,是一种无连接的协议。

UDP的特点有:无连接、尽最大努力交付、面向报文、没有拥塞控制

本文讲的回响服务器是指客户端向服务器发送一个报文,从服务器那里得到一条一模一样的回响报文

该代码需要在同一个包下创建两个类,服务器UdpEchoServer类,客户端UdpEchoClient类

2、服务器端代码

(1)完整代码

先放上完整代码

java">import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UdpEchoServer {
    public static DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        //手动指定服务器端口号
        socket = new DatagramSocket(port);
    }

    public static void start() throws IOException {
        while (true){
            System.out.println("服务器启动");

            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);

            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            String response = process(request);

            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);

            System.out.printf("[%s:%d] req:%s,resp:%s",requestPacket.getAddress(),requestPacket.getPort(),request,response);
            System.out.println();
        }
    }

    public static String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpServer server = new UdpServer(9090);
        server.start();
    }

}

(2)代码讲解

构造方法中手动指定服务器端口号

java">public UdpEchoServer(int port) throws SocketException {
    //手动指定服务器端口号
    socket = new DatagramSocket(port);
}

start()方法中进行信息的接收、处理、发送 

java">public static void start() throws IOException {
        while (true){
            System.out.println("服务器启动");

            //创建接收报文,用socket进行接收请求报文
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);

            //将请求报文转化为请求字符串,用process()方法进行处理,得到响应字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            String response = process(request);

            //将得到的响应字符串转化为响应报文,并用socket进行发送
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);

            //打印客户端IP地址和端口号信息
            System.out.printf("[%s:%d] req:%s,resp:%s",requestPacket.getAddress(),requestPacket.getPort(),request,response);
            System.out.println();
        }
}

process()方法

直接返回接收到的字符串

java">public static String process(String request){
        return request;
}

3、 客户端代码

 (1)完整代码

java">import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    public static DatagramSocket socket = null;
    private static String ip = null;
    private static int port = 0;

    public UdpEchoClient(String ip,int port) throws SocketException {
        //系统自动为客户端分配端口
        socket = new DatagramSocket();
        this.ip = ip;
        this.port = port;
    }

    public static void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.print("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(ip),port);
            socket.send(requestPacket);

            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);

            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}

(2)代码讲解

客户端由于可能有多个,所以需要系统自动为客户端分配端口

当初始化socket时,客户端还需要记下服务器端的ip和端口 

java">public static DatagramSocket socket = null;
private static String ip = null;
private static int port = 0;

public UdpEchoClient(String ip,int port) throws SocketException {
        //系统自动为客户端分配端口
        socket = new DatagramSocket();
        //记录ip和端口号
        this.ip = ip;
        this.port = port;
}

start()方法 

java">public static void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.print("->");
            String request = scanner.next();

            //将读取到的字符串转化为请求报文,并用socket进行发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(ip),port);
            socket.send(requestPacket);

            //创建回应报文来接收响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);

            //将响应报文转换成字符串,并打印出来
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
}


http://www.niftyadmin.cn/n/5260981.html

相关文章

DevExpress WinForms Pivot Grid组件,一个类似Excel的数据透视表控件(二)

界面控件DevExpress WinForms的Pivot Grid组件是一个类似Excel的数据透视表控件,用于多维(OLAP)数据分析和跨选项卡报表。在上文中(点击这里回顾>>)我们介绍了DevExpress WinForms Pivot Grid组件的性能、分析服务、数据塑造能力等&…

Docker Compose入门:打造多容器应用的完美舞台

Docker Compose 是一个强大的工具,它允许开发者通过简单的 YAML 文件定义和管理多容器的应用。本文将深入讨论 Docker Compose 的基本概念、常用命令以及高级应用场景,并通过更为丰富和实际的示例代码,助您轻松掌握如何通过 Docker Compose 打…

[LCTF 2018]bestphp‘s revenge

文章目录 前置知识call_user_func()函数session反序列化PHP原生类SoapClient 解题步骤 前置知识 call_user_func()函数 把第一个参数作为回调函数调用 eg:通过函数的方式回调 <?php function barber($type){echo "you wanted a $type haircut, no problem\n";}c…

uniapp 单选按钮 选中默认设备

需求1&#xff1a;选中默认设备&#xff0c;113 和114 和139都可以选中一个默认设备 选中多个默认设备方法&#xff1a; async toSwitch(typeItem, title) {const res await this.setDefaultDev(typeItem.ibdr_devsn, typeItem.ibdr_pid)if (!res) {this.common.toast(切换默…

跳跃游戏 + 45. 跳跃游戏 II

给你一个非负整数数组 nums &#xff0c;你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标&#xff0c;如果可以&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 示例 1&#xff1a; 输…

原创 macbook RN 环境搭建(实测心得)

这里的依赖除了 Watchman 都是必须安装的&#xff0c; 按照文档来的时候到 创建的时候 npx react-nativelatest init AwesomeProject 可能会触发错误&#xff0c;因为这是使用的默认的自带的ruby版本&#xff0c;虽然文件模板被创建了&#xff0c;会报错&#xff0c;后期也无…

成都工业学院2021级操作系统专周课程设计FCFS,SSTF,SCAN,LOOK算法的实现

运行环境 操作系统&#xff1a;Windows 11 家庭版 运行软件&#xff1a;CLion 2023.2.2 源代码文件 #include <iostream> #include <vector> #include <algorithm> #include <random> using namespace std;// 生成随机数 int generateRandomNumber…

回归预测 | MATLAB实现CHOA-BiLSTM黑猩猩优化算法优化双向长短期记忆网络回归预测 (多指标,多图)

回归预测 | MATLAB实现CHOA-BiLSTM黑猩猩优化算法优化双向长短期记忆网络回归预测 &#xff08;多指标&#xff0c;多图&#xff09; 目录 回归预测 | MATLAB实现CHOA-BiLSTM黑猩猩优化算法优化双向长短期记忆网络回归预测 &#xff08;多指标&#xff0c;多图&#xff09;效果…