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
}
}
*
------