首页 > 其他 > 详细

网络编程(一)

时间:2014-03-15 23:35:14      阅读:634      评论:0      收藏:0      [点我收藏+]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
发送端:
 
package demo_03_15;
 
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
 
import demo_03_14.inetAddress;
 
public class UDPsend {
    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("发送数据中…………");
         
        //第一步:创建UDPSocket
        DatagramSocket ds = new DatagramSocket();
         
        //第二步:创建InetAddress对象
        InetAddress ip = InetAddress.getByName("localhost");
         
        //第三步:创建UDP数据包
 
        String data = "fuck you java , php , python";
        byte[] buf = data.getBytes();
        DatagramPacket dp = new DatagramPacket(buf, buf.length, ip, 9000);
         
        //第四步:发送UDP数据包
        ds.send(dp);
         
        //第五步:关闭资源
        ds.close();
    }
 
}
 
 
 
 
 
接收端:
 
package demo_03_15;
 
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
 
public class UDPreceive {
 
    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("接收数据中…………");
         
        //第一步:创建接收udpsocket
        DatagramSocket ds = new DatagramSocket(10000);
         
        //第二步:创建存储包的udppacket
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf,buf.length);
         
        ds.receive(dp);  //阻塞式
         
        //第三步:解析接收到的udp包
        String host = dp.getAddress().getHostName();
        int port = dp.getPort();
        String data = new String(dp.getData(),0,dp.getLength());
         
        //第四步:关闭资源
        ds.close();
         
        System.out.println(host+" "+port+" "+data);
    }
 
}

  

网络编程(一),布布扣,bubuko.com

网络编程(一)

原文:http://www.cnblogs.com/justphp/p/3602461.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!