UDP通信Java编程

udp通信   接收端 的编写步骤:
1、新建套接 DatagramSocket  并绑定相应端口  
2、新建DatagramPackt 用于接收从发送端传过来的数据包
3、调用receive方法接收

package com.ldl.udptest;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpReceive {

    public static void main(String[] args) {
        DatagramSocket ds = null;
        try{
            ds = new DatagramSocket(20000);                                             //监听端口号
            while(true){
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length); //
                ds.receive(dp);                                                                         //单用receive方法接收
                buf = dp.getData();
                String data = new String(buf, 0, dp.getLength());               
                System.out.println(data);
//                System.out.println("data:"+data+"   port:"+port+"   ip:"+ip);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(ds!=null){
                ds.close();                                                                      //关闭套接字
            }
        }
    }

}


发送端

package com.ldl.udptest;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpSend {
     public static void main(String[] args) {
          BufferedReader br = null;          
          DatagramSocket ds = null;
          try{
              ds = new DatagramSocket();
              while(true){
              br = new BufferedReader(new InputStreamReader(System.in));    //新建一个缓冲流读取键盘输入
              byte[] buf = new byte[1024];                                  //由于DatagramPacket中需要byte参数
              buf = br.readLine().getBytes();
              DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.191.2"),20000);//四个参数分别是读取到输入的数组,数组长度,接收端IP地址,端口号
              ds.send(dp);                                                  //调用send方法发送
              InetAddress ip = InetAddress.getLocalHost();                  //获取本地IP
//            System.out.println("本机的IP地址为:"+ip);
              }
          }catch(Exception e){
              e.printStackTrace();
          }finally{
              if(ds !=null){
                   ds.close();
              }
          }
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值