java udp 简单实现

java udp 简单实现


------

代码:

 

 

* 运行方法:

      直接 运行 UdpTest.java 的 main 函数 即可,

 


* udp server

 

package eric.j2se.net.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

/**
 * udp server
 * 
 * @author eric
 * @date 2011-2-20 下午05:05:55
 */
public class UdpServer implements Runnable {
	private int port;

	public UdpServer(int port) {
		this.port = port;
	}

	public void run() {
		try {
			// listening at port for udp request
			DatagramSocket server = new DatagramSocket(new InetSocketAddress(port));
			byte[] bs = new byte[4];
			ByteBuffer bbuf = null;
			DatagramPacket data = new DatagramPacket(bs, bs.length);
			server.setSoTimeout(1000 * 10); // set timeout
			while (true) { // 一直监听
				server.receive(data);
				bbuf = ByteBuffer.wrap(bs, 0, 4);
				String s = "receive " + data.getData().length + " byte data,value: " + bbuf.getInt();
				System.out.println(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new Thread(new UdpServer(11111)).start();
	}
}

 
* udp client

 

package eric.j2se.net.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * udp client
 * 
 * @author eric
 * @date 2011-2-20 下午05:15:05
 */
public class UdpClient implements Runnable {
	private int port;

	public UdpClient(int port) {
		this.port = port;
	}

	public void run() {
		try {
			DatagramSocket client = new DatagramSocket();
			byte[] bs = new byte[4];
			InetSocketAddress isa = new InetSocketAddress("localhost", port);
			DatagramPacket data = new DatagramPacket(bs, bs.length);
			data.setSocketAddress(isa);
			for (int i = 0; i < 10; i++) {
				data.setData(int2bytes(i));
				client.send(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static byte[] int2bytes(int num) {
		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			b[i] = (byte) (num >>> (24 - i * 8));
		}
		return b;
	}
}

 


* test

 

package eric.j2se.net.udp;

/**
 * test udp
 * 
 * @author eric
 * @date 2011-2-20 下午05:43:06
 */
public class UdpTest {
	public static void main(String[] args) throws InterruptedException {
		int port = 11111;

		new Thread(new UdpServer(port)).start();// start udp server,listen request
		new Thread(new UdpClient(port)).start();// start udp client,send data
	}
}

 

 

------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值