【发布时间】:2020-07-06 07:48:40
【问题描述】:
我正在尝试连接到服务器套接字(Node Js),但我无法这样做。
您在https://socket.io/get-started/chat/ 上完成了教程,它可以正常工作。但是,当我通过 nativescript 或 https://www.websocket.org/echo.html 之类的 Web 客户端执行此操作时,它无法连接。
节点 Js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
// this is the culprit:
app.get('/', function(req:any, res:any){
res.sendFile(__dirname+"/index.html")
});
io.on('connection', function(socket:any){
console.log('a user connected');
socket.on('chat message', function(msg:any){
console.log('message: ' + msg);
});
});
http.listen(3001, function(){
console.log('listening on',3001);
})
Index.html 来自 socket.io 的示例
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
</body>
</html>
Main-page.ts
import { SocketIO, connect } from 'nativescript-socketio';
const server = "http://my-domain";
connect(server);
socketIO = new SocketIO(server);
socketIO.connect();
socketIO.on("error", error => {
console.log("A2", error)
});
【问题讨论】:
标签: node.js sockets nativescript nativescript-plugin