一个简单的UDP服务端和客户端示例

UDP的理论不再多说,我这里直接给出一个关于UDP的HelloWorld程序,代码明了,希望对刚入门的学生有所帮助!

当然,实际上,在这块我也刚入门!

 

首先写服务端代码,服务端邦定本地的IP和端口来监听访问:

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[1024];
	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和端口!

看一看客户端代码:

package udp;

import java.io.*;
import java.net.*;

/**
 * UDP客户端程序,用于对服务端发送数据,并接收服务端的回应信息
 */
public class UdpClientSocket {
	private byte[] buffer = new byte[1024];

	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[dp.getLength()];
		System.arraycopy(dp.getData(), 0, data, 0, dp.getLength());		
		return data;
	}
}

 

 直接运行程序看效果!

 

请您到ITEYE看我的原创:http://cuisuqiang.iteye.com

或支持我的个人博客,地址:http://www.javacui.com

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值