UDP:socket服务端和接收端的基本使用实例

来源:互联网 发布:在淘宝网上怎么买彩票 编辑:程序博客网 时间:2024/06/04 18:03

服务端代码:

package com.franky.net;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPSendClient {public static void main(String[] args) throws IOException {//1.建立socket发送端服务器DatagramSocket ds = new DatagramSocket();//2.确定发送的内容,IP地址,端口,并包装成数据包String str= "UDP服务端发送的数据!";byte[] buf = str.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);//3.发送数据ds.send(dp);//4.关闭服务ds.close();}}
接收端代码:

package com.franky.net;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class UDPRecClient {/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException {//1.建立socket接收端服务器,并指定接收的端口号DatagramSocket ds = new DatagramSocket(10000);//2.建立接收数据的数据包包对象byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);//3.用数据包接收数据,并获取数据包内的地址,端口号,内容等信息ds.receive(dp);int port = dp.getPort();String ip = dp.getAddress().getHostAddress();byte[] data = dp.getData();String str = new String(data, 0, dp.getLength());System.out.println("ip:"+ip+"part:"+port+"data:"+str);//4.关闭服务ds.close();}}



0 0
原创粉丝点击