【问题标题】:How to connect a socket with android using wifi direct如何使用wifi直接将套接字与android连接
【发布时间】:2014-12-02 20:50:11
【问题描述】:

我正在尝试使用 wifi 直接连接到从客户端到服务器的套接字,因此我在服务器上有此代码:

 ServerSocket serverSocket = new ServerSocket(2009);
 Socket client = serverSocket.accept();

我在客户端上有这段代码

final WifiP2pDevice peer = wifiP2pDeviceList.get("aMacAddress");
          WifiP2pConfig config = new WifiP2pConfig();
                            config.deviceAddress=peer.deviceAddress;
                            mManager.connect(mChannel,config,new WifiP2pManager.ActionListener() {
                                @Override
                                public void onSuccess() {
                                    mManager.requestGroupInfo(mChannel,new WifiP2pManager.GroupInfoListener() {
                                        @Override
                                        public void onGroupInfoAvailable(WifiP2pGroup group) {

                                            try {
                                                Socket socket = new Socket();

                                                int port = 2009;

                                                int timeout = 5000;
                                                socket.bind(null);

                                                socket.connect((new InetSocketAddress(peer.deviceAddress, port)), SOCKET_TIMEOUT); // Error here
                                        }
                                            catch (IOException e){

                                                e.printStackTrace();
                                            }

我可以直接使用 MAC 地址还是我的其他解决方案?

【问题讨论】:

  • 哪个设备的MAC地址?

标签: android sockets android-wifi serversocket wifi-direct


【解决方案1】:

Socket 通信需要 InetAddress 而不是 deviceAddress 字符串。

socket.connect((new InetSocketAddress(address, port)), SOCKET_TIMEOUT);

连接后即可获取groupOwnerAddress(WIFIP2P只能获取此IP地址)。

mManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {
    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        InetAddress address = wifiP2pInfo.groupOwnerAddress;
        //socket communication
    }
});

所有设备都可以获取此地址。向该地址发送消息,groupOwner 可以从套接字获取您的 IP。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-09
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多