【发布时间】:2015-11-28 07:27:50
【问题描述】:
我在使用 wifi direct 时遇到问题。我设法连接了 2 台设备并将数据从客户端发送到组所有者,因为组所有者 ip 是每个人都知道的。我还设法找出客户端的 IP 并将其传递给组所有者,但我无法将组所有者的数据发送给客户端,即使它应该是 simmetric。我使用Intent 和startService() 发送数据和AsynkTask 接收。仅使用 2 台设备,我注意到客户端 IP 始终相同(192.168.49.10),因此我手动将其赋予意图。
这是我尝试为所有者创建发送者和为客户端创建接收者的方法:
@Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
// InetAddress from WifiP2pInfo struct.
InetAddress groupOwnerAddress = info.groupOwnerAddress;
connected = true;
ownerIP = groupOwnerAddress.getHostAddress();
// After the group negotiation, we can determine the group owner.
if (info.groupFormed && info.isGroupOwner) {
Toast.makeText(MainActivity.this, "I'm the owner!!", Toast.LENGTH_SHORT).show();
owner = true;
// Do whatever tasks are specific to the group owner.
// One common case is creating a server thread and accepting
// incoming connections.
Intent serviceIntent = new Intent(MainActivity.this, OwnerSender.class);
serviceIntent.setAction(OwnerSender.ACTION_SEND);
serviceIntent.putExtra(OwnerSender.EXTRAS_CLIENT_ADDRESS,"192.168.49.10");
serviceIntent.putExtra(OwnerSender.EXTRAS_CLIENT_PORT, 8988);
startService(serviceIntent);
//new OwnerReceiver(this).execute(); // owner riceve dai client sulla porta 8988
} else if (info.groupFormed) {
// The other device acts as the client. In this case,
// you'll want to create a client thread that connects to the group
// owner.
/*Intent serviceIntent = new Intent(MainActivity.this, ClientSender.class);
serviceIntent.setAction(ClientSender.ACTION_SEND);
serviceIntent.putExtra(ClientSender.EXTRAS_GROUP_OWNER_ADDRESS,ownerIP);
serviceIntent.putExtra(ClientSender.EXTRAS_GROUP_OWNER_PORT, 8988);
startService(serviceIntent);*/
new ClientReceiver(this).execute(); // i client ricevono dall'owner sula porta 8989
Toast.makeText(MainActivity.this, "I'm a client...", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Server IP: " + groupOwnerAddress.getHostAddress(), Toast.LENGTH_SHORT).show();
}
}
此方法在连接建立时启动,并且所有者应该启动服务以发送数据,但服务永远不会启动。我已经说过了,如果在客户端使用相同的服务并且数据从客户端正确传输到所有者,则会启动相同的服务。
【问题讨论】:
-
客户端连接后,必须通过socket通信向群主发送消息什么的(他们知道群主IP)。组所有者可以从套接字读取客户端 IP。存储IP,就可以向客户端发送数据了。
-
起初我尝试将数据从客户端发送给所有者,并且效果很好。我存储了客户端的IP并尝试将数据从所有者发送到客户端,但它不起作用。我注意到,对于 2 台设备,客户端的 IP 始终相同(192.168.49.10)。在上面的示例中,我尝试在建立连接后直接从所有者发送到客户端。由于客户端的IP一直都是一样的,所以我直接给服务了,但是无论如何都不管用。
-
我不明白为什么服务不想启动。我很确定客户端的IP是正确的,并且端口(8988)与我用来从客户端向所有者发送数据的端口相同。
-
@MatteoBernardon 发现了什么?
-
@MatteoBernardon 嘿,你解决了这个问题吗?
标签: android service wifi-direct owner