当前位置: 首页 > article >正文

第三百三十节 Java网络教程 - Java网络UDP服务器

Java网络教程 - Java网络UDP服务器

以下代码显示了如何编写UDP回显服务器:

DatagramSocket socket  = new DatagramSocket(12345);
DatagramPacket packet  = new DatagramPacket(new byte[1024],  1024);
while(true)  {
    // Receive   the   packet socket.
    receive(packet);
    
    //Send back  the   same packet to the   sender socket.
    send(packet);
}

Echo 服务器

基于UDP套接字的Echo服务器

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

public class Main {
  public static void main(String[] args) throws Exception {
    final int LOCAL_PORT = 12345;
    final String SERVER_NAME = "localhost";
    DatagramSocket udpSocket = new DatagramSocket(LOCAL_PORT,
        InetAddress.getByName(SERVER_NAME));

    System.out.println("Created UDP  server socket at "
        + udpSocket.getLocalSocketAddress() + "...");
    while (true) {
      System.out.println("Waiting for a  UDP  packet...");
      DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
      udpSocket.receive(packet);
      displayPacketDetails(packet);
      udpSocket.send(packet);
    }
  }
  public static void displayPacketDetails(DatagramPacket packet) {
    byte[] msgBuffer = packet.getData();
    int length = packet.getLength();
    int offset = packet.getOffset();

    int remotePort = packet.getPort();
    InetAddress remoteAddr = packet.getAddress();
    String msg = new String(msgBuffer, offset, length);

    System.out.println("Received a  packet:[IP Address=" + remoteAddr
        + ", port=" + remotePort + ", message=" + msg + "]");
  }
}

上面的代码生成以下结果。

Echo 客户端

基于UDP套接字的Echo客户端

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
  public static void main(String[] args) throws Exception {
    DatagramSocket udpSocket = new DatagramSocket();
    String msg = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter a  message  (Bye  to quit):");
    while ((msg = br.readLine()) != null) {
      if (msg.equalsIgnoreCase("bye")) {
        break;
      }
      DatagramPacket packet = Main.getPacket(msg);
      udpSocket.send(packet);
      udpSocket.receive(packet);
      displayPacketDetails(packet);
      System.out.print("Please enter a  message  (Bye  to quit):");
    }
    udpSocket.close();
  }
  public static void displayPacketDetails(DatagramPacket packet) {
    byte[] msgBuffer = packet.getData();
    int length = packet.getLength();
    int offset = packet.getOffset();
    int remotePort = packet.getPort();
    InetAddress remoteAddr = packet.getAddress();
    String msg = new String(msgBuffer, offset, length);
    System.out.println("[Server at IP  Address=" + remoteAddr + ", port="
        + remotePort + "]: " + msg);
  }
  public static DatagramPacket getPacket(String msg)
      throws UnknownHostException {
    int PACKET_MAX_LENGTH = 1024;
    byte[] msgBuffer = msg.getBytes();

    int length = msgBuffer.length;
    if (length > PACKET_MAX_LENGTH) {
      length = PACKET_MAX_LENGTH;
    }
    DatagramPacket packet = new DatagramPacket(msgBuffer, length);
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    packet.setAddress(serverIPAddress);
    packet.setPort(15900);
    return packet;
  }
}

上面的代码生成以下结果。


http://www.kler.cn/a/404616.html

相关文章:

  • AI赋能:PPT制作的创意革命
  • 2021 年 3 月青少年软编等考 C 语言三级真题解析
  • OpenMMlab导出Mask R-CNN模型并用onnxruntime和tensorrt推理
  • (C语言)文件操作
  • AJAX的基本使用
  • 连锁SPA馆拥抱数字化转型:多门店系统赋能高效运营
  • uni-app快速入门(十)--常用内置组件(下)
  • 查看docker日志 journalctl -u docker.service
  • Modern Effective C++ Item 11:优先考虑使用deleted函数而非使用未定义的私有声明
  • Webserver回顾
  • 【AI知识】两类最主流AI应用(文生图、ChatGPT)中的目标函数
  • React第五节 组件三大属性之 props 用法详解
  • ts: 定义一个对象接收后端返回对象数据,但是报错了有红色的红线为什么
  • 安全测试必学神器 --BurpSuite 安装及使用实操
  • Go 工具链详解(八):go telemetry
  • Wallpaper壁纸制作学习记录05
  • 【JavaSE 网络编程和日期与时间知识总结】
  • Java Web应用中的跨站请求伪造(CSRF)防御策略
  • 关于一次开源java spring快速开发平台项目RuoYi部署的记录
  • hj 212 协议解包php解包,
  • 从0开始的数据结构速过——番外(1)
  • ubuntu20.04如何升级python3.8到python3.10
  • React 组件中 State 的定义、使用及正确更新方式
  • 本地git多用户ssh配置
  • Adobe XD文件处理:即时设计的在线解决方案
  • 腾讯云存储COS上传视频报错