我坚持在通过wifi创建Android手机(2.3)和我的电脑之间的UDP连接。
我知道如何在本地服务器中创建UDP连接。我的问题是做android支持adhock网络,因为每当我尝试直接搜索我的PC的wifi时,它都没有显示它,因此我必须首先在我的PC上创建一个虚拟热点,然后将我的手机连接到它。
在此之后,我只是尝试将数据包从手机发送到PC上运行的服务器。
public class WifitestActivity extends Activity {
WifiManager w;
TextView status;
InetAddress server_ip;
int server_port = 9876;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
status = (TextView) findViewById(R.id.status);
w = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (!w.isWifiEnabled()) {
status.setText("switching ON wifi ");
w.setWifiEnabled(true);
} else {
status.setText("Its already ON ");
}
int x;
WifiInfo info = w.getConnectionInfo();
status.append("\n\nWiFi Status: " + info.toString());
x = info.getIpAddress();
String str = info.getMacAddress();
status.append("\n\nmac address===" + str + " ,ip===" + x);
try {
server_ip = InetAddress.getByName("192.168.181.1"); // ip of my server.How to dynamically update it
} catch (UnknownHostException e) {
status.append("Error at fetching inetAddress");
}
DatagramSocket s = new DatagramSocket(server_port, server_ip);
// **ERROR AT PREVIOUS LINE, I HAD TO FORCE STOP MY APP EVERTIME I RUN
// MY CODE**
String str = "TEST MESSAGE !!!";
byte b1[];
b1 = new byte[100];
b1 = str.getBytes();
DatagramPacket p1 = new DatagramPacket(b1, b1.length, server_ip,
server_port);
}
}
在我的电脑上运行的服务器代码:
import java.io.*;
import java.net.*;
class server2
{
static InetAddress clientip;
static int clientport;
static DatagramPacket p3;
public static void main(String args[])throws Exception
{
DatagramSocket s = new DatagramSocket(9876);
byte b1[],b2[];
b1=new byte[100];
b2=new byte[100];
DatagramPacket p1 = new DatagramPacket(b1,b1.length);
s.receive(p1);
b1=p1.getData();
String str = new String( b1);
clientport = p1.getPort(); //packet mein save hota hai
clientip=p1.getAddress();
System.out.println("RECIEVED FROM CLIENT IP ="+clientip+" port="+clientport+" data="+str);
}
}
客户端代码(WifiTestActivity)出错,每当我尝试在手机上运行时,我的应用都会崩溃。 Plzz帮助我!
答案 0 :(得分:0)
您需要Internet Permission。将此添加到您的清单:
<uses-permission android:name="android.permission.INTERNET"/>