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
}
}
*
——
分享到:
2011-02-20 18:36
浏览 9879
评论
今天的文章java udp 工具类_java udp 简单实现分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/25723.html