使用Nearby Connections,每个设备都有一个endpointId,类似于zkHk
。
获取其他人的endpointId是微不足道的,因为它在扫描或连接到其他设备时由API返回。
我必须错过一些东西,但我找不到一种方法来获得我自己的endpointId(除了实现一个连接的对等体回应我的id的机制)。对于某些我希望关注发送给谁的协议,它可能很有用。
我发现的唯一的东西是getLocalEndpointName
,但它返回我的名字,而不是我的身份。即使它似乎the C++ version of Nearby have it!
你对Java / Kotlin有什么想法吗?我特意寻求获取endpointId,而不是使用替代方法,例如在localendpoint名称中使用一种GUID作为替代。
编辑:一些使用示例
1)例如,实现一些网络网格协议可能很有趣。有几个设备相互连接,形成一个全局网络,每个设备在再次发送之前将其endpointId
添加到传入的有效载荷中,因此其他设备可以检查是否应将有效负载发送到已有它的设备。
2)我可能还想特意发送一个数据包从设备A到C到B作为中继,并在有效负载中添加一些“from:A”和“to:C”字段,以便网络知道如何路由数据并避免一些重传周期。使用endpointId
更简单,因为每个设备都有一个与之连接的endpointId
列表。
3)调试目的也很有趣。如果我使用连接到其他几个手机的电话(例如星形网络)进行一些测试,那么如果我想将name
用于其他目的,则更容易知道新的数据来自哪个手机。
注意:所有这些都可以不同的方式完成(例如,为设备的“名称”使用一些唯一的标识符,并检查而不是endpointId
),但它似乎有点麻烦。因为endpointId
保证了一种单一性,所以更多,而我必须为name
强制执行它。此外,在交换数据之前,我在其他设备上没有很多信息(只有endpointId
和name
),所以如果我使用name
替代endpointId
,我觉得我删除了我的最后一个元数据槽。
截至今天,您无法获得自己的端点ID。我们没有看到你需要它的原因。您能否提供一个更详细的算法示例,您需要知道自己的ID?
我想你想获得你的endpointId并将其发送到其他设备再次认识你?如是
让我们这样想:其他设备将获得您的EndpointID并在每次连接时保存它
1)你有一个Arrylist<EndPointObject> listOfUsers
,其中EndPointObject
它是一个Object包含有关Connected Endpoint Device的信息(你创建这个类)。我们将使用此Arry列表来保存收到的Endpoint信息
2)你需要通过实现Serializable
使EndPointObject类Serializable,你这样做是为了使它能够转换为Byte []并在有效载荷中发送它
public class EndPointObject implements Serializable
{
String endpointId ;
.
.
.
}
3)这是Converting类将它添加到您的项目中
public class SerializeHelperForPayLoad {
public static byte[] serialize(Object object) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
// transform object to stream and then to a byte array
objectOutputStream.writeObject(object);
objectOutputStream.flush();
objectOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException{
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
return objectInputStream.readObject();
}
}
4)现在策略是每次连接到端点设备时,您将交换您的EndpointObject信息,因此在payloadcallback中
PayloadCallback mPayloadCallback =
new PayloadCallback() {
@Override
public void onPayloadReceived(String endpointId, Payload payload) {
if (payload.getType() == Payload.Type.BYTES) {
try{
onDataReceived(endpointId, SerializeHelperForPayLoad.deserialize(payload.asBytes()));
} catch (IOException | ClassNotFoundException e) { e.getMessage(); }
}
}
// onData recieved void
void onDataReceived(String endpointId, Object object) {
// do something with your Object
EndPointObject recieved_user_info = new EndPointObject();
if (object.getClass() == EndPointObject.class){
//casting
recieved_user_info = (EndPointObject) object;
//now add his end pointid to his information
recieved_user_info.setEndpointId(endpointId);
listOfUsers.add(recieved_user_info);
}
}
我在附近的技术方面很新,但我希望这有帮助,通过这种方式你可以要求其他终端端点每次都发送你自己的endpointid