UDP的数据传输

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xxdw1992/article/details/78621265

一.准备工作

 

   private static DatagramSocket dSocket;
    private static InetAddress inetAddress;//表示互联网协议(IP)地址
    private static WifiManager.MulticastLock lock = BaseApplication.lock;

 

    public static WifiManager.MulticastLock lock;
    public static WifiManager wfm;
  // 有的手机不能直接接收UDP包,可能是手机厂商在定制Rom的时候把这个功能给关掉了。实例化一个WifiManager.MulticastLock
  // 对象lock, 在调用广播发送、接收报文之前先调用lock.acquire()方法;
  // 用完之后及时调用lock.release()释放资源,否决多次调用lock.acquire()方法,程序可能会崩.
        wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        lock = wfm.createMulticastLock("wifi lcb");

 

 

InetAddress类

 

Java.net包中有InetAddress类的定义,InetAddress类的对象用于IP地址和域名,该类提供以下方法:
getByName(String s):获得一个InetAddress 类的对象,该对象中含有主机的IP地址和域名,该对象用如下格式表示它包含的信息:www.sina.com.cn/202.108.37.40;
 
String getHostName():获取InetAddress对象的域名;
 
String getHostAddress():获取InetAddress对象的IP地址;
 

getLocalHost():获得一个InetAddress对象,该对象含有本地机的域名和IP地址。

 

二.向服务器发送数据

 

 

public static String Send(String ip, int port, byte[] data) {
        try {
            //在给定主机名的情况下确定主机的IP地址,如果参数为null,获得的是本机的IP地址
            inetAddress = InetAddress.getByName(ip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Logs.i("udputil 25    " + e);
        }
        try {
            dSocket = new DatagramSocket();
            dSocket.setSoTimeout(10000);// 如果对方连接状态10秒没有收到数据的话强制断开客户端
        } catch (SocketException e) {
            e.printStackTrace();
            Logs.i("udputil 32    " + e);
        }
        // 创建一个DatagramPacket对象,用于发送数据。
        // 参数一:要发送的数据 参数二:数据的长度 参数三:服务端的网络地址 参数四:服务器端端口号
        DatagramPacket dPacket = new DatagramPacket(data, data.length, inetAddress, port);
        try {
            dSocket.send(dPacket);
            Logs.i(dPacket.getAddress() + "  udputil 45  " + dPacket.getPort());
//            Logs.i("udputil 47    " + Arrays.toString(dPacket.getData()));
        } catch (IOException e) {
            e.printStackTrace();
            Logs.i("udputil 50    " + e);
        }
        String s = Recevice();
        return s;
    }


三.从服务器接收数据

 

 

private static String Recevice() {
        String result = "NO RESPONSE";
        byte[] dataRec = new byte[66];
        DatagramPacket dPacket = new DatagramPacket(dataRec, dataRec.length);
        try {
            lock.acquire();
            dSocket.receive(dPacket);
            lock.release();
            result = new String(dPacket.getData());
//            Logs.i("udputil 66          " + result + "\n" + Arrays.toString(dPacket.getData()));
        } catch (IOException e) {
            e.printStackTrace();
            Logs.i("udputil 69    " + e);
        }
        dSocket.close();
        return result;
    }

 

 

 

 

 

四.DatagramSocket的方法

 

1.      InputStream      getInputStream()     从socket中获取输入流

2.      OutputStream  getOutputStream() 从socket中获取输出流

3.      int              getLocalPort()     获取本地的端口,端口用于监听服务器端的返回值,如果没绑定则为-1

4.      int              getPort()    获取连接的服务器端的连接端口,如果没连接则为0

5.      InetAddress    getInetAddress()  获取另一端的IP地址,toString后为/加上IP地址。

6.      InetAddress     getLocalAddress()  获取本地的IP地址,toString后如:/10.0.11.204

7.      SocketAddress  getRemoteSocketAddress()获取另一端的IP和端口,toString后如:/10.0.11.204:8808

8.      SocketAddress getLocalSocketAddress()  获取本地的IP和端口,toString后如:/10.0.11.204:3513

9.      Int         getReceiveBufferSize() 获取接收端Socket的缓冲大小,默认是8kb.有get就有set。

10.   Boolean    isBound       是否此套接字绑定到本地地址和端口


五.整个UDP传输的大致流程

 

如果做为客户端,调用顺序应该是这样。
dSocket = new DatagramSocket();

//但作为服务器的话DatagramSocket(端口)要添加端口号


inetAddress = InetAddress.getByName(svrIpAddress);


DatagramPacket dPacket = new 

DatagramPacket(byData, length, inetAddress, svrPort);


dSocket.send(dPacket);

 

 

 

 

展开阅读全文

udp实现数据传输的问题

09-09

想用Java实现简单的UDP数据传输 但是服务器端老报错 Address already in use: Cannot bindrn下面是代码 帮忙看下 谢谢rn/******************客户端**********************************/rnpublic static void main(String[] args) throws java.io.IOExceptionrn rn rn String localhost ="192.168.108.200";rn rn BufferedInputStream inFromUser = rn new BufferedInputStream(new FileInputStream("c:\\test.txt"));rn rn DatagramSocket clientSocket = new DatagramSocket();rn InetAddress IPAddress = InetAddress.getByName(localhost);rn rn byte[] sendData = new byte[1024];rn byte[] receiveData = new byte[1024];rn //read data from inFromUser to sendDatarn while(inFromUser.read(sendData)!=-1)rn rn DatagramPacket sendPacket = rn new DatagramPacket(sendData, sendData.length, IPAddress, 8000);rn clientSocket.send(sendPacket);rnrn rn inFromUser.close();rn clientSocket.close();rn rnrnrnrn/***********************服务器端********************/rnrn public static void main(String[] args) throws Exception rn rn BufferedOutputStream bufferedOutputStream = rn new BufferedOutputStream(new FileOutputStream("d:\\test.txt"));rn DatagramSocket serverSocket = new DatagramSocket(8000);rn byte[] receiveData = new byte[1024];rn byte[] sendData =new byte[1024];rn rn DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);rn serverSocket.receive(receivePacket);rn rn while(true)//循环的条件不知道该怎么定就用true了rn rn bufferedOutputStream.write(receivePacket.getData());rn rn rn 论坛

UDP数据传输时的问题

07-31

我使用UDP在客户端与服务器端进行交互:rn/******************************client side*****************************/rn byte[] buf =new byte[256];rn int port =0;rn String fileName =args[2];//从main中带入的第三个参数,用于打开服务器端文件。rn InetAddress address =null;rn DatagramSocket clientSocket=null;rn DatagramPacket clientPacket=null;rn //convert host from name to ip addressrn address=InetAddress.getByName(args[0]);rn //Set up a socketrn clientSocket=new DatagramSocket();rn port=Integer.parseInt(args[1]);rn //put filename into bufrn buf=fileName.getBytes();rn //send requestrn clientPacket=new DatagramPacket(buf,buf.length,address,port);rn clientSocket.send(clientPacket);rn/*******************server side**********************************/rn int port =0;rn byte[] buf =new byte[256];rn String fileName =null;rn InetAddress address =null;rn DatagramSocket serverSocket=null;rn DatagramPacket serverPacket=null;rn //set up socketrn port=Integer.parseInt(args[0]);rn serverSocket=new DatagramSocket(port);rn //listeningrn serverPacket=new DatagramPacket(buf, buf.length);rn serverSocket.receive(serverPacket);rn //get file namern int c=-1,i=0;rn while ((c=buf[i])!=0)rn fileName=fileName+(char)c;rn i++;rn rn/****************************end ***********************/rn//删除了对exception的处理。rn rn我现在的问题是,这样得到的文件名总在前面有个null,rn如客户输入student.txt, 服务器端得到的字符串是nullstudent.txt.rn我找不出null是哪来的 论坛

没有更多推荐了,返回首页