一直都是通过OkHttp远程服务端进行数据交互,突发奇想能不能也通过OkHttp在局域网的情况下对两个安卓设备或者手机进行数据交互呢?
这样一方安卓设备要当做服务端与另一个安卓设备通过OkHttp进行数据交互即可
当然还可以通过 socket 和 ServerSocket 通过发送TCP 实现两个安卓设备的数据交互
Android之间互传消息之ServerSocket,Android服务端接收Socket发送的TCP
省流—> 以下代码借鉴以下链接
AndServer配置
【Android】 使用AndServer框架在手机上搭建服务器
AndServer文档地址
首先是Java版本的,亲测可运行
网上大多数我都看过了,基本都是有问题的,可能别人或其他楼主可以运行,但是到我这里不行,大概是他们的AS版本太久远了~~~
第一步,先看一下我的目录结构,需要改动的地方我都标出来了,原理,怎么实现的我也没研究源码,作为一个白嫖客,我拿过来能正常使用我就笑了,嘤嘤嘤。
由上到下,网络权限必不可少
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity,布局文件就俩Button,你都开始研究Server了,不会还想连俩按钮的xml都想白嫖吧????
public class MainActivity extends AppCompatActivity {private Button button1,button2;private ServerManager serverManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button1 = findViewById(R.id.button_start);button2 = findViewById(R.id.button_stop);serverManager = new ServerManager(this);button1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {serverManager.startServer();}});button2.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {serverManager.stopServer();}});}
}
ServerManager
public class ServerManager {private Server mServer;private static final String TAG = "ServerManager";/*** Create server.*/public ServerManager(Context context) {InetAddress inetAddress = null;try {//这里的ip地址是手机的ip地址,可通过手机设置>系统->关于手机查看inetAddress = InetAddress.getByName("192.1.1.1");} catch (UnknownHostException e) {e.printStackTrace();}mServer = AndServer.serverBuilder(context).inetAddress(inetAddress).port(8080).timeout(10, TimeUnit.SECONDS).listener(new Server.ServerListener() {@Overridepublic void onStarted() {Log.i(TAG, "onStarted: 服务器启动");}@Overridepublic void onStopped() {Log.i(TAG, "onStopped: 服务器关闭");}@Overridepublic void onException(Exception e) {Log.i(TAG, "onException: 服务器出现异常"+e.getMessage());}}).build();}/*** Start server.*/public void startServer() {if (mServer.isRunning()) {// TODO The server is already up.} else {mServer.startup();}}/*** Stop server.*/public void stopServer() {if (mServer.isRunning()) {mServer.shutdown();} else {Log.w("AndServer", "The server has not started yet.");}}
}
UserController,有几篇文章,使用这里面的注解的时候,提示找不到对应的注解,那是他们博主使用的版本太老了,更新最新的版本试下哈
@RestController
public class UserController {@GetMapping("/123")String login() {Log.i(TAG, "login: 收到消息");return "你好啊兄弟";}
}
以上就是代码,以下是配置文件,跟紧了,快上车!!!!
一开始这里没添加,编译没问题,一直卡在运行了,错误日志里也提示了,就是搞不懂,谁能想到还得加一这块啊,如果你的AS版本这里不是 plugins-id 的形式的而是 classpath 的形式,往下分,看一下 Kotlin 写法的配置去~
buildscript {repositories {mavenCentral()google()}dependencies {classpath 'com.yanzhenjie.andserver:plugin:2.1.9' // AndServer}
}
plugins {id 'com.android.application' version '7.4.2' apply falseid 'com.android.library' version '7.4.2' apply false
}
有一说一,咱虽然不知道这咋写的,小配件还整挺多
id 'com.yanzhenjie.andserver' // AndServer
implementation 'com.yanzhenjie.andserver:api:2.1.12'annotationProcessor 'com.yanzhenjie.andserver:processor:2.1.12'
运行试下(192.1.1.1:8080/123),别忘了改成自己的手机IP
以下是Kotlin写法
老样子先看目录结构
网络权限少不了
<uses-permission android:name="android.permission.INTERNET"/>
AndServerEngine
object AndServerEngine {private var mAndServer: Server? = nullfun startup() {if (mAndServer?.isRunning == true) {Log.i("ABCD", "AndServer已经启动")return}AndServer.webServer(App.sContext).port(8899).timeout(10, TimeUnit.SECONDS).listener(object : Server.ServerListener {override fun onStarted() {Log.i("ABCD", "AndServer启动成功")}override fun onStopped() {Log.i("ABCD", "AndServer关闭成功")}override fun onException(e: Exception?) {Log.i("ABCD", "AndServer出现异常", e)}}).build().apply {mAndServer = thisstartup()}}fun shutdown() {val server = mAndServerif (server?.isRunning == true) {server.shutdown()mAndServer = null} else {Log.i("ABCD", "AndServer没有启动")}}}
App,这里是原作者写在清单文件中的 name
class App : Application() {companion object {lateinit var sContext: App}override fun onCreate() {super.onCreate()sContext = this}
}
MainActivity 俩按钮,一个开一个关
class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)findViewById<Button>(R.id.startBtn).setOnClickListener { AndServerEngine.startup() }findViewById<Button>(R.id.stopBtn).setOnClickListener { AndServerEngine.shutdown() }}
}
UserController
@RestController
@RequestMapping(path = ["/user"])
class UserController {//192.1.1.1:8899/user/login?account=Test&password=123456@GetMapping("/login")fun login(@QueryParam("account") account: String?, @QueryParam("password") password: String?): String {Log.i("ABCD", "收到登录请求,account = $account,password = $password")return "Successful!"}}
以上是代码部分,以下是配置,上车!上车!
buildscript {repositories {google()mavenCentral()}dependencies {classpath "com.android.tools.build:gradle:7.4.2"classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"classpath 'com.yanzhenjie.andserver:plugin:2.1.9' // AndServer// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files}
}task clean(type: Delete) {delete rootProject.buildDir
}
id 'com.yanzhenjie.andserver' // AndServer
// AndServerimplementation 'javax.activation:javax.activation-api:1.2.0'implementation 'com.yanzhenjie.andserver:api:2.1.9'kapt 'com.yanzhenjie.andserver:processor:2.1.9'