六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 89|回复: 0

最简单的UDP编程

[复制链接]

升级  15.67%

75

主题

75

主题

75

主题

举人

Rank: 3Rank: 3

积分
247
 楼主| 发表于 2013-1-15 08:12:20 | 显示全部楼层 |阅读模式
接收端:
import java.io.*;import java.net.*;public class TestUDPServer {public static void main(String[] args) throws Exception{byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);DatagramSocket ds = new DatagramSocket(5678);while(true){ds.receive(dp);ByteArrayInputStream bis = new ByteArrayInputStream(buf);DataInputStream dis = new DataInputStream(bis);System.out.println(dis.readLong());}}}  
发送端:
import java.io.*;import java.net.*;public class TestUDPClient{public static void main(String[] args) throws Exception{long n = 10000L;ByteArrayOutputStream bos = new ByteArrayOutputStream();DataOutputStream dos = new DataOutputStream(bos);dos.writeLong(n);byte[] buf = bos.toByteArray();DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));DatagramSocket ds = new DatagramSocket(9999);ds.send(dp);ds.close();}} 
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表