---
title: "java udp简单例子"
author: "jiang_xiaohan"
date: "2012-10-18T14:50:28Z"
tags: []
categories: ["编程语言"]
slug: "java-udp"
draft: false
lastmod: "2012-10-18T17:27:13Z"
id: 1700976
url: "https://jiang-xiaohan.iteye.com/blog/1700976"
---

====转载====
一个简单的UDP服务端和客户端示例

博客分类： 网络编程
socketudptcp网络端口
UDP的理论不再多说，我这里直接给出一个关于UDP的HelloWorld程序，代码明了，希望对刚入门的学生有所帮助！

 
首先写服务端代码，服务端邦定本地的IP和端口来监听访问：
Java代码  
package udp;  
  
import java.io.IOException;  
import java.net.DatagramPacket;  
import java.net.DatagramSocket;  
import java.net.InetSocketAddress;  
  
/** 
 * UDP服务类 
 */  
public class UdpServerSocket {  
      
    private byte buffer = new byte;  
    private static DatagramSocket ds = null;  
    private DatagramPacket packet = null;  
    private InetSocketAddress socketAddress = null;  
      
    /** 
     * 测试方法 
     */  
    public static void main(String args) throws Exception {  
        String serverHost = "127.0.0.1";  
        int serverPort = 3344;  
        UdpServerSocket udpServerSocket = new UdpServerSocket(serverHost,  
                serverPort);  
        while (true) {  
            udpServerSocket.receive();  
            udpServerSocket.response("你好,吃了吗!");  
        }         
    }  
  
    /** 
     * 构造函数，绑定主机和端口 
     */  
    public UdpServerSocket(String host, int port) throws Exception {  
        socketAddress = new InetSocketAddress(host, port);  
        ds = new DatagramSocket(socketAddress);  
        System.out.println("服务端启动!");  
    }  
  
    /** 
     * 接收数据包，该方法会造成线程阻塞 
     */  
    public final String receive() throws IOException {  
        packet = new DatagramPacket(buffer, buffer.length);  
        ds.receive(packet);  
        String info = new String(packet.getData(), 0, packet.getLength());  
        System.out.println("接收信息：" + info);  
        return info;  
    }  
  
    /** 
     * 将响应包发送给请求端 
     */  
    public final void response(String info) throws IOException {  
        System.out.println("客户端地址 : " + packet.getAddress().getHostAddress()  
                + ",端口：" + packet.getPort());  
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length, packet  
                .getAddress(), packet.getPort());  
        dp.setData(info.getBytes());  
        ds.send(dp);  
    }  
}  
 
运行后提示服务端运行成功，程序开始监听端口，接收方法堵塞，当有访问时才会向下进行！
 
我们写客户端进行访问，看到网上的例子都是直接创建了 DatagramSocket 对象，而其实自己都不知道自己使用的端口是那个，这里我创建时会指定自己邦定的端口，其实很简单，就是初始化该对象时传递一个端口参数。
这里你访问客户端时客户端会打印你的IP和端口！
看一看客户端代码：
Java代码  
package udp;  
  
import java.io.*;  
import java.net.*;  
  
/** 
 * UDP客户端程序，用于对服务端发送数据，并接收服务端的回应信息 
 */  
public class UdpClientSocket {  
    private byte buffer = new byte;  
  
    private static DatagramSocket ds = null;  
      
    /** 
     * 测试客户端发包和接收回应信息的方法 
     */  
    public static void main(String args) throws Exception {  
        UdpClientSocket client = new UdpClientSocket();  
        String serverHost = "127.0.0.1";  
        int serverPort = 3344;  
        client.send(serverHost, serverPort, ("你好，亲爱的!").getBytes());  
        byte bt = client.receive();  
        System.out.println("服务端回应数据：" + new String(bt));  
        // 关闭连接  
        try {  
            ds.close();  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    }  
  
    /** 
     * 构造函数，创建UDP客户端 
     */  
    public UdpClientSocket() throws Exception {  
        ds = new DatagramSocket(8899); // 邦定本地端口作为客户端  
    }  
      
    /** 
     * 向指定的服务端发送数据信息 
     */  
    public final void send(final String host, final int port,  
            final byte bytes) throws IOException {  
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(host), port);  
        ds.send(dp);  
    }  
  
    /** 
     * 接收从指定的服务端发回的数据 
     */  
    public final byte receive()  
            throws Exception {  
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length);  
        ds.receive(dp);       
        byte data = new byte;  
        System.arraycopy(dp.getData(), 0, data, 0, dp.getLength());       
        return data;  
    }  
}  
 
 
直接运行程序看效果！