灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:3197回复:0

java例程练习(网络编程[简单UDP通信试验])

楼主#
更多 发布于:2012-09-08 09:44

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

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);
        
        ByteArrayInputStream bais = new ByteArrayInputStream(buf);
        
        
        while(true) {
            DataInputStream dis = new DataInputStream(bais);
            ds.receive(dp);//阻塞式的
            //System.out.println(new String(buf, 0, dp.getLength()));
            System.out.println(dis.readLong());
        }
    }
}
[java]
import java.net.*;
import java.io.*;
public class TestUDPClient {
    public static void main(String[] args) throws Exception{
        //向服务器端传一个long类型数字
        long n = 10000;
        ByteArrayOutputStream baos =  
                    new ByteArrayOutputStream();
        DataOutputStream DOS = new DataOutputStream(baos);
        DOS.writeLong(n);
        byte [] buf = baos.toByteArray();
        
        
        
        //byte [] buf = (new String("hello")).getBytes();
        
        DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1",5678));
        DatagramSocket ds = new DatagramSocket(9999);
        ds.send(dp);
        ds.close();
    }
}


摘自 Yours风之恋


喜欢0 评分0
游客

返回顶部