本文共 2754 字,大约阅读时间需要 9 分钟。
通过NSD_SERVICE连接
其中一台设备作为服务端,需要向NSD_SERVICE注册服务,另一台设备作为客户端,通过NSD_SERVICE搜索服务,连接服务,连接之后就可以通过Socket通信了。
向NSD_SERVICE注册服务:
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName("NsdChat");
serviceInfo.setServiceType("_http._tcp.");
serviceInfo.setPort(SERVER_PORT);
nsdManager.registerService(
serviceInfo, NsdManager.PROTOCOL_DNS_SD, new NsdManager.RegistrationListener() {
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "nsdRegist onRegistrationFailed: " + errorCode);
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "nsdRegist onUnregistrationFailed: " + errorCode);
}
@Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
Log.d(TAG, "nsdRegist onServiceRegistered");
}
@Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
Log.d(TAG, "nsdRegist onServiceUnregistered");
}
});
serviceType 用于客户端搜索时的检索条件
SERVER_PORT为端口号,客户端能获取到,服务端Socket也是监听这个端口(这段代码就不贴了)
客户端代码
搜索设备
nsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, new NsdManager.DiscoveryListener() {
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "discoverNsdService onStartDiscoveryFailed " + errorCode);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "discoverNsdService onStopDiscoveryFailed " + errorCode);
}
@Override
public void onDiscoveryStarted(String serviceType) {
Log.d(TAG, "discoverNsdService onDiscoveryStarted");
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.d(TAG, "discoverNsdService onDiscoveryStopped");
}
@Override
public void onServiceFound(NsdServiceInfo serviceInfo) {
Log.d(TAG, "discoverNsdService onServiceFound");
resolveService(serviceInfo);
}
@Override
public void onServiceLost(NsdServiceInfo serviceInfo) {
Log.d(TAG, "discoverNsdService onServiceLost");
}
});
连接设备
nsdManager.resolveService(serviceInfo, new NsdManager.ResolveListener() {
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "resolveService onResolveFailed " + errorCode);
}
@Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.d(TAG, "resolveService onServiceResolved");
sendSocketNsd(serviceInfo);
}
});
发送Socket信息
try {
Socket socket = new Socket(serviceInfo.getHost(), serviceInfo.getPort());
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
outputStream.writeUTF("from haha usb oo ");
String str = inputStream.readUTF();
Log.d(TAG, "socket receive: " + str);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
转载地址:http://gujkl.baihongyu.com/