Android库. 1 UDP客户端

package com.qinxiaoyu.lib.transmit.net.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import com.qinxiaoyu.lib.Debug;

public class UdpClient {

    private static final String tag = "UdpClient";
    private static void debug(String msg)
    {
        if(Debug.debugTransimtNetUdpUdpClient)
            Debug.debugx(tag, msg);
    }

    public static void send(String ip,int port,byte[] data) throws Exception
    {
        DatagramSocket socket = new DatagramSocket();  
        DatagramPacket packet = new DatagramPacket(data, data.length,InetAddress.getByName(ip), port);  
        socket.send(packet); 
        socket.close();
    }
    /**
     * 通过udp将一串数据发送至指定ip地址的指定端口<hr>
     * @author    秦晓宇
     * @date      2015年2月27日 
     * @param ip    -发送方的ip地址
     * @param port  -对方的接收端口
     * @param data  -发送的数据
     * @return
     *          -发送成功则返回true<br>
     *          -发送失败返回false。
     */
    public static boolean send(String ip,int port,String data) // throws Exception
    {
        DatagramSocket socket;
        try 
        {
            debug("send");
            socket = new DatagramSocket();
            byte buffer[] = data.getBytes();
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length,InetAddress.getByName(ip),port);  
            socket.send(packet);
            socket.close();
            return true;
        } 
        catch (SocketException e) 
        {
            // TODO Auto-generated catch block
            debug("SocketException");
            e.printStackTrace();
            return false;
        } catch (Exception e) 
        {
            // TODO Auto-generated catch block
            debug("Exception");
            e.printStackTrace();
            return false;
        }  

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值