第三百三十节 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;
  }
}

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

相关推荐
网络安全(king)5 分钟前
【Python】【持续项目】Python-安全项目搜集
开发语言·python·安全
工业甲酰苯胺6 分钟前
Python脚本消费多个Kafka topic
开发语言·python·kafka
Str_Null9 分钟前
Seatunnel运行时报错Caused by: java.lang.NoClassDefFoundError: com/mysql/cj/MysqlType
java·seatunnel
麻花201317 分钟前
C#之WPF的C1FlexGrid空间的行加载事件和列事件变更处理动态加载的枚举值
开发语言·c#·wpf
麻花201322 分钟前
WPF里面的C1FlexGrid表格控件添加RadioButton单选
java·服务器·前端
_黎明29 分钟前
【Swift】字符串和字符
开发语言·ios·swift
理想不理想v36 分钟前
【经典】webpack和vite的区别?
java·前端·javascript·vue.js·面试
C++忠实粉丝38 分钟前
计算机网络socket编程(2)_UDP网络编程实现网络字典
linux·网络·c++·网络协议·计算机网络·udp
请叫我青哥39 分钟前
第五十二条:谨慎使用重载
java·spring
添砖java_85744 分钟前
UDP数据报套接字编程
网络·网络协议·udp