Cordova 与 Node.js Sockect.io Server 连接

Cordova connect with Node.js Sockect.io Server

提问人:Hamude Salman 提问时间:11/15/2023 更新时间:11/15/2023 访问量:10

问:

“我正在尝试让我的 Cordova 应用程序与使用 Node.js 构建的 Socket.io 服务器通信,但它不起作用!我使用 Cordova 制作了一个移动应用程序,并使用 Node.js 和 Socket.io 设置了一个实时通信服务器。但是,当我尝试连接它们时,它并没有发生。

我需要一些帮助来弄清楚出了什么问题。如果您对如何将 Cordova 应用程序连接到 Socket.io 服务器有任何建议,或者我可能会犯一些常见错误,我将非常感谢您的帮助。

非常感谢!

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
  attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
    <meta
      name="viewport"
      content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"
    />
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <meta name="msapplication-tap-highlight" content="no" />
    <title>Hello World</title>
  </head>
  <body>
    <div class="app">
      <h1>Apache Cordova</h1>
      <div id="deviceready" class="blink">
        <p class="event listening">Connecting to Device</p>
        <p class="event received">Device is Ready</p>
      </div>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script
      type="text/javascript"
      src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"
    ></script>
    <script type="text/javascript" src="js/index.js"></script>
  </body>
</html>

Javascript/科尔多瓦

document.addEventListener("deviceready", function () {
  try {
    const socket = io("https://chat-ten-umber.vercel.app");
    socket.on("connect", function () {
      alert("Yeeeeeeeee");
      socket.on("text", function (text) {
        alert(text);
      });
    });
  } catch (err) {
    alert(err);
  }
});

服务器:

const express = require("express");
const app = express();
const http = require("http").Server(app);
const cors = require("cors");
const io = require("socket.io")(http);

app.use(cors());

io.on("connection", (socket) => {
  console.log("A user is connected");

  socket.on("disconnect", () => {
    console.log("The user disconnect");
  });

  socket.on("message", (data) => {
    console.log("Received message:", data);
    socket.broadcast.emit("message", { message: data.message, to: data.to });
  });
});

// start server
http.listen(8000, () => {
  console.log("Server running on port 8000");
});

app.get("/", (req, res, next) => {
  res.send("Hello");
});
JavaScript 节点.js react-native cordova socket.io

评论


答: 暂无答案