编写 Android 服务器与标准 Java 实现没有太大区别。
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket newClient = serverSocket.accept(); // block until new connection
<IO with newClient>
}
至于 IO 部分:你可以做标准阻塞 IO,这可能会
要求你产生额外的线程,或者你可以使用Android nio API
现在:
serverSocket 代码必须在专用线程上运行
如果您计划一个长期运行的服务器,您可能希望将它放在一个
专门的服务。由 Activity 直接产生的线程可能会被 Android 交换
在他们的活动移到后台之后。
在这方面服务要好得多。但服务最终也会下降。
因此,如果服务器对您的系统非常重要,您将需要一种方法
告诉 Android 在资源不足时不要杀死它。方法是声明你的服务
作为foreground service:
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
前台服务比标准服务更稳定,但不妨碍 Android 去
睡觉,当你睡觉时没有任何作用。如果你真的需要你的应用程序来防止设备进入睡眠状态,
您需要获得wake lock。唤醒锁在电池消耗方面非常昂贵。小心处理。
至于客户端代码(我假设是 Java 客户端)——它可能看起来像这样:
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
while (true) {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
<write to peer>
socket.close();
}
最后一个棘手的问题:您必须找出一种传递服务器 IP 地址的方法
对其同行。请记住 - 这是移动设备和您使用的网络
可以定期更改。要获取服务器 IP 地址,请使用:
String getDeviceIpAddr() {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface network = en.nextElement();
for (Enumeration<InetAddress> addr = network.getInetAddresses(); addr.hasMoreElements();) {
InetAddress inetAddress = addr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
}
您需要某种方式将其传递给服务器的客户端。许多人为此使用中继服务器。