java udp转发_【Java】UDP发包的简单实现

这个博客展示了如何使用Java实现UDP通信。`UdpClient`类创建了一个DatagramSocket,向指定IP和端口发送UTF-8编码的消息。`UdpServer`类在同一端口上监听,接收到消息后打印出来。通过运行这两个类,可以看到简单的UDP数据传输过程。
摘要由CSDN通过智能技术生成

最近在学Java,正好做一些笔记,以防止自己忘了。

client端

//UdpClient.java

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetSocketAddress;

import java.net.SocketException;

public class UdpClient {

private static DatagramSocket clientSocket = null;

private InetSocketAddress serverAddress = null;

public UdpClient(String host, int port) throws SocketException {

clientSocket = new DatagramSocket( ); //创建socket

serverAddress = new InetSocketAddress(host, port); //绑定sever的ip与port

}

public void send(String msg) throws IOException {

try {

byte[] data = msg.getBytes("utf-8");

DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress);

clientSocket.send(packet);

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//main方法用于测试

public static void main(String[] args) throws Exception {

UdpClient client = new UdpClient("127.0.0.1", 14586);

client.send("hello world");

clientSocket.close();

}

}

server端

//UdpServer.java

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.SocketException;

public class UdpServer {

private byte[] data = new byte[1024];

private static DatagramSocket serverSocket = null;

private DatagramPacket packet = null;

public UdpServer(int port) throws SocketException {

serverSocket = new DatagramSocket(port);

System.out.println("sever start!");

}

//接收消息

public String recieve() throws IOException {

packet = new DatagramPacket(data, data.length);

serverSocket.receive(packet);

String info = new String(packet.getData(), 0, packet.getLength());

System.out.println("recieve message from " + packet.getAddress().getHostAddress()

+ ":" + packet.getPort() + "\t"+ info);

return info;

}

//本地测试

public static void main(String[] args) throws Exception {

UdpServer server = new UdpServer(14586);

server.recieve();

}

}

打印结果

sever start!

recieve message from 127.0.0.1:64478 hello world

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值