从PC(Windows)(客户端)发送udp消息到Android手机(服务器)无法正常工作

时间:2015-05-27 10:28:18

标签: android multithreading udp

我想使用WIFI连接从PC(服务器)向我的Android手机4.2(客户端)发送UDP消息。我的手机和PC通过无线路由器连接。但是从手机到手机没有收到任何消息。 我从调试中了解到程序正在socket.receive(packet);等待。因此,UI上没有更新。 我想在服务器收到来自客户端的消息时向UI显示消息,此过程将继续。

如果你能帮助我,我将不胜感激。谢谢。我已经添加了必要的许可。

服务器:

package com.example.abuttontest;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.System;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;




public class MainActivity extends Activity 
{
    private TextView tv;
    int i =0;
    // String s;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button button1 = (Button) findViewById(R.id.button1);
         tv = (TextView) findViewById(R.id.textView1);
        //TextView textMessage = (TextView) findViewById(R.id.textView2);




        button1.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) 
            {
                /*cheack ping message*/
                //boolean morgan= isOnline();
                //String s = String.valueOf(morgan);
                tv.setText("kkkkkkkkkk");   // print ping message

                Log.d("MyTag@","This is sample log message");

            }

        });

        /* Thread for receiving Data from CLient */
        runThread();


    }


    private void runThread()
    {

        new Thread()
        {

            public void run()
            {
                 Log.d("p2p", "1");
                while (i++ < 1000) 
                {
                    Log.d("p2p", "2");
                    try {
                        /////////////////////
                        //System.out.println("aaa");
                        byte[] inbuf = new byte[1000]; // default size
                        DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
                        Log.d("p2p", "3");
                        DatagramSocket socket = new DatagramSocket(6000);
                        socket.receive(packet);
                        Log.d("p2p", "4");
                        int numBytesReceived = packet.getLength();
                        //System.out.println(numBytesReceived);
                         String s = new String(inbuf);
                        //System.out.println(s);
                        //System.out.println(inbuf[2]);

                        socket.close();

                        Log.d("p2p", "5");


                        runOnUiThread(new Runnable() 
                        {

                            @Override
                            public void run()
                            {
                                tv.setText("#" + i);
                            }
                        });
                        Thread.sleep(300);
                    } 
                    catch (InterruptedException e) 
                    {
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }





    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.one)
        {
            Toast.makeText(getApplicationContext(), "Toast Message ONE", Toast.LENGTH_LONG).show();

        }
        if (id == R.id.two)
        {
            Toast.makeText(getApplicationContext(), "Toast Message TWO", Toast.LENGTH_LONG).show();
        }
        if (id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }











}

客户端:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*packets in the IP layer are called the datagrams */
/*After creating a packet, the process of sending or receiving it involves calling the send or receive method of DatagramSocket. More specifically, you create a packet, then you create a socket. After you create the socket, you call the send method of DatagramSocket to send the datagram packet or use the receive method of DatagramSocket to receive a packet. You can also use the same DatagramSocket to send and receive multiple packets, each going to different destinations and coming from different sources.*/
public class client
{
    public static void main(String args[])
    {
        System.out.println("from client");


        try{
            //InetAddress ipaddress = InetAddress.getByName("localhost");
        //  InetAddress ipaddress = InetAddress.getByName("192.168.0.103");
//      while(true)
//      {
            InetAddress ipaddress = InetAddress.getByName("192.168.0.102");
            int port = 6000;
            //byte[] buffer = new byte[1024]; // empty byte array
            String msg ="hello goooooooogle"; // send this message to the server
            byte [] b_array = msg.getBytes();

            //on SERVER side DatagramSocket able to receive packets on 8080 port
            DatagramPacket packet = new DatagramPacket(b_array, b_array.length, ipaddress, port);// DatagramPacket(byte[], byte_length, InetAddress, port_number)
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();
//      }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在您的MainActivity中,您没有提到服务器必须侦听的端口号。