关于Android利用局域网进行UDP通信的问题

我写了一个小程序准备利用UDP和电脑之间进行通信,然后基于这个做一点东西,可是问题是我用AVD测试很好用的,但是用真机测试就是不行。
我的思路是让电脑和Android设备连接一台路由器,路由器为两台设备分配固定的ip地址进行通信。
拜托大家帮我看看啊,我这才是第一步就郁闷的要死
下面是代码。
1:MainActivity

package com.company.zebork.testudpll;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

EditText text;
Button send;
Handler handler;
Message msg;
EditText ad;
String address;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (EditText) findViewById(R.id.editText);
    send = (Button) findViewById(R.id.send);
    ad = (EditText) findViewById(R.id.editText2);
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            text.setText("");
        }
    };

/* send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handler.handleMessage(msg);
}
});*/

    send.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            System.out.println(ad.getText().toString());
            AsyncTask<String ,String , Void> toSend = new AsyncTask<String, String, Void>() {
                @Override
                protected Void doInBackground(String... params) {

                    address = ad.getText().toString();
                    UDPClient client = new UDPClient(address);
                    System.out.println("here" + address);
                    client.send(text.getText().toString());
                    msg = new Message();
                    handler.sendMessage(msg);
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {

                    super.onPostExecute(aVoid);
                }
            }.execute(address);
        }
    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

2、UDPClient

package com.company.zebork.testudpll;

import java.io.IOException;
import java.net.*;
public class UDPClient {

private DatagramPacket dp;
private DatagramSocket ds;
private byte[] buf;
private String address;

public UDPClient(String address) {
    buf = new byte[4096];
    this.address = address;
    System.out.println("??" + address);
    try {
        ds = new DatagramSocket(8888);
    } catch (SocketException e) {
        e.printStackTrace();
    }
}

public void send(String str) {
    buf = str.getBytes();
    try {
        dp = new DatagramPacket(buf, buf.length,new InetSocketAddress(address,5679));
        ds.send(dp);
        ds.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

3、AndroidManifest【有些权限我都没有用到,因为调试这个错误才加上的】

<?xml version="1.0" encoding="utf-8"?>
package="com.company.zebork.testudpll" >




<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

4、activity_main.xml

xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/editText2"
    android:layout_gravity="center_horizontal"
    android:text="ip" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="发送"
    android:id="@+id/send"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal" />

5、服务器的Java文件,我是用JavaSE写的,因为不会javaEE
import java.io.IOException;
import java.net.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestUDPClient extends Frame{

private static DatagramPacket dp;
private static DatagramSocket ds;
private static TextField text;
private static TextArea ta;
public static void main(String[] args) {

    Frame f = new TestUDPClient();
    f.setLocation(200, 200);
    f.setSize(300,200);
    f.setVisible(true);

    text = new TextField();
    ta = new TextArea();
    f.add(text,BorderLayout.SOUTH);
    f.add(ta,BorderLayout.CENTER);
    f.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            if(ds!=null)
                ds.close();
            System.exit(0);
        }

    });
    startServer();

}

public static void startServer() {

    byte[] buf = new byte[4096];
    dp = new DatagramPacket(buf,buf.length);

    try {
        ds = new DatagramSocket(5679);
    } catch (SocketException e) {
        e.printStackTrace();
    }
    while(true) {
        try {
            ds.receive(dp);

            if(ta.getText().length() > 0)
                ta.setText(ta.getText() + "\n" + new String(buf,0,dp.getLength()));
            else
                ta.setText(new String(buf,0,dp.getLength()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}

1个回答

先看是否分配到合法IP,然后就是建立连接是否成功

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐