mine.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <view class="container">
  3. <text>服务端IP:</text>
  4. <input v-model="serverIp" placeholder="192.168.1.100" />
  5. <button @click="scan">🔍 自动扫描</button>
  6. <button @click="connect">🚀 连接</button>
  7. <text v-if="scanning">扫描中...</text>
  8. </view>
  9. </template>
  10. <script>
  11. export default {
  12. data() {
  13. return {
  14. serverIp: uni.getStorageSync('serverIp') || '',
  15. scanning: false
  16. };
  17. },
  18. methods: {
  19. async scan() {
  20. if (this.scanning) return;
  21. this.scanning = true;
  22. const ip = await this.scanNetwork();
  23. if (ip) {
  24. this.serverIp = ip;
  25. uni.showToast({ title: '发现: ' + ip });
  26. } else {
  27. uni.showToast({ icon: 'none', title: '未发现' });
  28. }
  29. this.scanning = false;
  30. },
  31. async scanNetwork() {
  32. // 1. 试上次 IP
  33. const lastIp = uni.getStorageSync('serverIp');
  34. if (lastIp && await this.testIp(lastIp)) {
  35. return lastIp;
  36. }
  37. // 2. 获取网段
  38. const prefix = this.getNetworkPrefix();
  39. // 3. 扫描 1-50
  40. for (let i = 1; i <= 50; i++) {
  41. const ip = `${prefix}${i}`;
  42. if (await this.testIp(ip)) {
  43. return ip;
  44. }
  45. await this.delay(100);
  46. }
  47. return null;
  48. },
  49. testIp(ip) {
  50. return new Promise(resolve => {
  51. uni.request({
  52. url: `http://${ip}:8811/ping`,
  53. timeout: 3000,
  54. success: res => {
  55. resolve(res.statusCode === 200 ? ip : null);
  56. },
  57. fail: () => resolve(null)
  58. });
  59. });
  60. },
  61. getNetworkPrefix() {
  62. let prefix = '192.168.1.';
  63. if (typeof plus !== 'undefined' && plus.networkinfo) {
  64. const ip = plus.networkinfo.getIPAddress();
  65. if (ip) prefix = ip.replace(/\.\d+$/, '.') + '.';
  66. }
  67. return prefix;
  68. },
  69. delay(ms) {
  70. return new Promise(resolve => setTimeout(resolve, ms));
  71. },
  72. connect() {
  73. if (!this.serverIp) {
  74. uni.showToast({ icon: 'none', title: '请先设置IP' });
  75. return;
  76. }
  77. uni.setStorageSync('serverIp', this.serverIp);
  78. uni.connectSocket({ url: `ws://${this.serverIp}:8811` });
  79. uni.onSocketOpen(() => {
  80. 'link';
  81. });
  82. }
  83. }
  84. };
  85. </script>