udp连接到设备

时间:2012-10-30 11:43:49

标签: android multithreading sockets udp datagram

这是我的代码

package com.example.messenger;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
    Button Send;
    EditText IPAdresse;
    EditText TEXT;
    TextView RXtext,tstep,rstep;
    private static final int TIMEOUT_MS = 1000;
    private static final int server_port = 13011;

    @SuppressLint({ "NewApi", "NewApi", "NewApi" })
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 

        IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
        IPAdresse.setText("192.168.2.32");
        TEXT = (EditText) findViewById(R.id.etTEXT);
        Send = (Button) findViewById(R.id.bSendaa);
        RXtext = (TextView) findViewById(R.id.tvRXtext);
        tstep = (TextView) findViewById(R.id.tvTstep);
        rstep = (TextView) findViewById(R.id.tvRstep);
        Send.setOnClickListener(this);


        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                String text;
                byte[] message = new byte[1500];
                DatagramSocket s;

                while(true){
                try {
                    s= new DatagramSocket(server_port);
                    rstep.setText("1");
                    s.setBroadcast(true);
                    rstep.setText("2");
                    s.setSoTimeout(TIMEOUT_MS);
                    rstep.setText("3");

                    while(true){
                        DatagramPacket p = new DatagramPacket(message, message.length);
                        rstep.setText("4");
                        //InetAddress test = InetAddress.getByName("192.168.1.101");
                        //rstep.setText("5");
                        //s.connect(test,12345);
                        //rstep.setText("6");
                        s.receive(p);
                        rstep.setText("xxx");
                        text = new String(message, 0, p.getLength());
                        RXtext.setText(text);
                    }
                } catch (SocketException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    rstep.setText("fail socket create");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    rstep.setText("fail receive");
                }

                }
            }
        });
        }

public void onClick(View arg0) {
    // TODO Auto-generated method stub
    switch(arg0.getId()){
    case R.id.bSendaa:
        tstep.setText("1");
        String messageStr= TEXT.getText().toString();
        tstep.setText("2");

        DatagramSocket s;
        try {
            s = new DatagramSocket();
            tstep.setText("3");
            s.setBroadcast(true);
            tstep.setText("4");
            s.setSoTimeout(TIMEOUT_MS);
            tstep.setText("5");
            InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
            tstep.setText("6");
            int msg_length=messageStr.length();
            tstep.setText("7");
            byte[] message = messageStr.getBytes();
            tstep.setText("8");
            DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
            tstep.setText("9");
            s.connect(local,server_port);
            tstep.setText("10");
            s.send(p);
            tstep.setText("sending complete");


        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            tstep.setText("sending failed");
        }
    }
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

我的Android手机的IP是192.168.2.32,我在wifi设置中看到它。因此,当我逐行调试时,我看到我的虚拟设备发送了数据包,但我不知道为什么我的手机无法获取它。有谁能够帮我? 谢谢 此致

1 个答案:

答案 0 :(得分:0)

现在它可以工作,我没有为线程调用start()函数,我应该从runOnUiThread更改UI,但它只能在设备之间工作,而不是从虚拟设备到设备,所以这是工作代码

package com.example.messenger;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
    Button Send;
    EditText IPAdresse;
    EditText TEXT;
    TextView RXtext,tstep,rstep;
    private static final int TIMEOUT_MS = 10000;
    private static final int server_port = 13011;
    String mMessage;

    @SuppressLint({ "NewApi", "NewApi", "NewApi" })
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 

        IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
        IPAdresse.setText("192.168.2.32");
        TEXT = (EditText) findViewById(R.id.etTEXT);
        Send = (Button) findViewById(R.id.bSendaa);
        RXtext = (TextView) findViewById(R.id.tvRXtext);
        tstep = (TextView) findViewById(R.id.tvTstep);
        rstep = (TextView) findViewById(R.id.tvRstep);
        Send.setOnClickListener(this);


        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                String text;
                byte[] message = new byte[4];
                DatagramSocket s;

                try {
                    s= new DatagramSocket(server_port);
                    s.setSoTimeout(TIMEOUT_MS);

                    while(true){
                        try {
                            DatagramPacket p = new DatagramPacket(message, message.length);
                            s.receive(p);

                            mMessage = new String(message, 0, p.getLength());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    RXtext.setText(mMessage);
                                }
                            });
                        }
                        catch(Exception e) {
                            e.printStackTrace();
                        }

                    }
                } catch (SocketException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    //rstep.setText("fail socket create");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    //rstep.setText("fail receive");
                }
            }

        }).start();
    } 

public void onClick(View arg0) {
    // TODO Auto-generated method stub
    switch(arg0.getId()){
    case R.id.bSendaa:
        String messageStr= TEXT.getText().toString();

        DatagramSocket s;
        try {
            s = new DatagramSocket();
            s.setBroadcast(true);
            s.setSoTimeout(TIMEOUT_MS);
            InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
            int msg_length=messageStr.length();
            byte[] message = messageStr.getBytes();
            DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
            //s.connect(local,server_port);
            s.send(p);
            tstep.setText("sending complete");


        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            tstep.setText("sending failed");
        }
    }
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}