发送和接收数据的UDP套接字的java的android [英] Send and receive data on UDP Socket java android

查看:196
本文介绍了发送和接收数据的UDP套接字的java的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够通过正确的UDP套接字发送我的数据,但是当我收到的数据是不断在接收命令等待我不知道是什么原因造成这
请看看下面

我的code

我能够从Android设备服务器端正确recive数据,但是当我从服务器端发送数据给Android设备没有收到。但是当我从服务器发送数据到任何其他客户端例如PC应用它接收并显示rpoperly数据

 类任务实现Runnable {
    @覆盖
    公共无效的run(){
        尝试{
            字符串messageStr =饲料;
            INT SERVER_PORT = 8888;
            InetAddress类本地= InetAddress.getByName(10.0.2.2);
            INT msg_length = messageStr.length();
            字节[]消息= messageStr.getBytes();
            DatagramSocket的S =新的DatagramSocket();
           //            DatagramPacket类P =新的DatagramPacket(消息,msg_length,地方,SERVER_PORT);
            s.send(对); //正确能够发送数据。我接收数据到服务器            的for(int i = 0; I< = 20;我++){
                最终int值=我;
                消息=新的字节[30000]
                P =新的DatagramPacket(消息,message.length);
                s.receive(P); //不断等候在这里,但我发送的数据从服务器返回,但是不会接收
                最后一个字节[]数据= p.getData();;
                尝试{                    视频下载(1000);
                }赶上(InterruptedException的E){
                    e.printStackTrace();
                }
                handler.post(新的Runnable(){
                    @覆盖
                    公共无效的run(){
                        progressBar.setProgress(值);
                        imageView.setImageBitmap(BitmapFactory.de codeByteArray的(数据,0,data.length));
                    }
                });
            }
        }
        赶上(异常前)
        {        }
    }
}


解决方案

在Eclipse文档:


  

从此套接字并将其存储在参数包接收的数据包。
  包的所有字段必须根据接收的数据来设置。如果
  接收的数据是比包缓冲区的大小不再是截断。
  此方法一直阻塞收到一个包或者超时
  过期。


s.receive(P); 命令块的线程,直到它receices数据或暂停时以setSoTimeout(超时)设置超过

我做了2班,使我的通讯发生。
首先UDP-服务器:

 进口java.net.DatagramPacket中;
进口java.net.DatagramSocket中;
进口android.annotation.Sup pressLint;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Build;公共类UDP_Server
{
    私人AsyncTask的<太虚,太虚,太虚>异步;
    私人布尔Server_aktiv = TRUE;    @燮pressLint(NewApi)
    公共无效runUdpServer()
    {
        异步=新的AsyncTask<太虚,太虚,太虚>()
        {
            @覆盖
            保护无效doInBackground(无效... PARAMS)
            {
                字节[] = lMsg新的字节[4096];
                DatagramPacket类DP =新的DatagramPacket(lMsg,lMsg.length);
                DatagramSocket的DS = NULL;                尝试
                {
                    DS =新的DatagramSocket(Main.SERVER_PORT);                    而(Server_aktiv)
                    {
                        ds.receive(DP);                        意图I =新意图();
                        i.setAction(Main.MESSAGE_RECEIVED);
                        i.putExtra(Main.MESSAGE_STRING,新的String(lMsg,0,dp.getLength()));
                        。Main.MainContext.getApplicationContext()sendBroadcast(ⅰ);
                    }
                }
                赶上(例外五)
                {
                    e.printStackTrace();
                }
                最后
                {
                    如果(DS!= NULL)
                    {
                        ds.close();
                    }
                }                返回null;
            }
        };        如果(Build.VERSION.SDK_INT> = 11)async.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        别的async.execute();
    }    公共无效stop_UDP_Server()
    {
        Server_aktiv = FALSE;
    }
}

我接收到的数据发送到广播接收器,并在那里,你可以做你想做的与数据什么都。

现在我的客户端发送的数据。在这个code I发送一个广播,但我认为这将是改变code发送到直接IP或东西没有问题的。

 进口java.net.DatagramPacket中;
进口java.net.DatagramSocket中;
进口android.annotation.Sup pressLint;
进口android.os.AsyncTask;
进口android.os.Build;公共类UDP_Client
{
    私人AsyncTask的<太虚,太虚,太虚> async_cient;
    公共字符串消息;    @燮pressLint(NewApi)
    公共无效NachrichtSenden()
    {
        async_cient =新的AsyncTask<太虚,太虚,太虚>()
        {
            @覆盖
            保护无效doInBackground(无效... PARAMS)
            {
                DatagramSocket的DS = NULL;                尝试
                {
                    DS =新的DatagramSocket();
                    DatagramPacket类DP;
                    DP =新的DatagramPacket(Message.getBytes(),Message.length(),Main.Bro​​adcastAddress,Main.SERVER_PORT);
                    ds.setBroadcast(真);
                    ds.send(DP);
                }
                赶上(例外五)
                {
                    e.printStackTrace();
                }
                最后
                {
                    如果(DS!= NULL)
                    {
                        ds.close();
                    }
                }
                返回null;
            }            保护无效onPostExecute(虚空结果)
            {
               super.onPostExecute(结果);
            }
        };        如果(Build.VERSION.SDK_INT> = 11)async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        别的async_cient.execute();
    }

和这里是你怎么从你的主类实例化类。

  //启动UDP服务器
        服务器=新UDP_Server();
        Server.runUdpServer();        // UDP客户ERSTELLEN
        客户端=新UDP_Client();

在这里,如何发送消息,该客户端。

  //设置消息
                Client.Message =您的信息;
                                    //发信息
                Client.NachrichtSenden();

要停止UDP_Server,只需设置Server.Server_aktiv为false。

要设置上述消息ü也可以写一个setMessage(字符串消息)梅索德或者类似的东西。

我希望这会帮助你=)。
而在去年对不起我的英语不好。 :D

I am able to properly send my data through UDP socket , but when i receive data it keeps on waiting at receive command i don't know what is causing this Please have a look at my code below

I am able to properly recive data at server side from android device, but when i send data from server side to android device it doesn't receive. but when i send data from server to any other client e.g PC application it receive and displays data rpoperly

class Task implements Runnable {
    @Override
    public void run() {
        try {
            String messageStr = "feed";
            int server_port = 8888;
            InetAddress local = InetAddress.getByName("10.0.2.2");
            int msg_length = messageStr.length();
            byte[] message = messageStr.getBytes();


            DatagramSocket s = new DatagramSocket();
           // 

            DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
            s.send(p);//properly able to send data. i receive data to server

            for (int i = 0; i <= 20; i++) {
                final int value = i;
                message = new byte[30000];
                p = new DatagramPacket(message,message.length );
                s.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
                final byte[] data =  p.getData();;
                try {



                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setProgress(value);
                        imageView.setImageBitmap(BitmapFactory.decodeByteArray(data,0,data.length));
                    }
                });
            }
        }
        catch(Exception ex)
        {

        }
    }
}

解决方案

Documentation in Eclipse:

Receives a packet from this socket and stores it in the argument pack. All fields of pack must be set according to the data received. If the received data is longer than the packet buffer size it is truncated. This method blocks until a packet is received or a timeout has expired.

The "s.receive(p);" command blocks the thread until it receices data or the timeout set with setSoTimeout(timeout) is over.

I have made 2 classes to make my communication happen. First UDP-Server:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;

public class UDP_Server 
{
    private AsyncTask<Void, Void, Void> async;
    private boolean Server_aktiv = true;

    @SuppressLint("NewApi")
    public void runUdpServer() 
    {
        async = new AsyncTask<Void, Void, Void>() 
        {
            @Override
            protected Void doInBackground(Void... params)
            {   
                byte[] lMsg = new byte[4096];
                DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
                DatagramSocket ds = null;

                try 
                {
                    ds = new DatagramSocket(Main.SERVER_PORT);

                    while(Server_aktiv)
                    {
                        ds.receive(dp);

                        Intent i = new Intent();
                        i.setAction(Main.MESSAGE_RECEIVED);
                        i.putExtra(Main.MESSAGE_STRING, new String(lMsg, 0, dp.getLength()));
                        Main.MainContext.getApplicationContext().sendBroadcast(i);
                    }
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                } 
                finally 
                {
                    if (ds != null) 
                    {
                        ds.close();
                    }
                }

                return null;
            }
        };

        if (Build.VERSION.SDK_INT >= 11) async.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else async.execute();
    }

    public void stop_UDP_Server()
    {
        Server_aktiv = false;
    }
}

I send the received data to an BroadcastReceiver and there you can do what ever you want to with the data.

And now my client to send the data. In this code i send a broadcast, but i think it will be no problem to change the code for sending to a direct IP or something.

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;

public class UDP_Client 
{
    private AsyncTask<Void, Void, Void> async_cient;
    public String Message;

    @SuppressLint("NewApi")
    public void NachrichtSenden()
    {
        async_cient = new AsyncTask<Void, Void, Void>() 
        {
            @Override
            protected Void doInBackground(Void... params)
            {   
                DatagramSocket ds = null;

                try 
                {
                    ds = new DatagramSocket();
                    DatagramPacket dp;                          
                    dp = new DatagramPacket(Message.getBytes(), Message.length(), Main.BroadcastAddress, Main.SERVER_PORT);
                    ds.setBroadcast(true);
                    ds.send(dp);
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
                finally 
                {
                    if (ds != null) 
                    {   
                        ds.close();
                    }
                }
                return null;
            }

            protected void onPostExecute(Void result) 
            {
               super.onPostExecute(result);
            }
        };

        if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else async_cient.execute();
    }

And here is how you instantiate the classes from your main class.

            //start UDP server
        Server = new UDP_Server();
        Server.runUdpServer();

        //UDP Client erstellen
        Client = new UDP_Client();

And here how to send a message with the client.

                                    //Set message
                Client.Message = "Your message";
                                    //Send message
                Client.NachrichtSenden();

To stop the UDP_Server, just set Server.Server_aktiv to false.

To set the message above u can also write a "setMessage(String message)" methode or something like that.

I hope this will help you =). And at last sorry for my bad english. :D

这篇关于发送和接收数据的UDP套接字的java的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆