[英]connect client to server using socket.io
I have a node.js basic server as follow: 我有一个node.js基本服务器,如下所示:
app.js file: app.js文件:
var express = require('express');
config = require('./config/config');
var app = express();
require('./config/express')(app, config);
var server = require('http').Server(app);
server.listen(config.port,function () {
console.log('Express server listening on port ' + config.port);
});
module.exports = server;
my port is 8001. 我的港口是8001。
and a deafult.ts file: 和一个deafult.ts文件:
import express = require('express');
var server = require('../../app');
var router = express.Router();
export = function (app) {
app.use('/', router);
};
router.get('/', function (req, res, next) {
res.render('index', {
title: 'hello world'
});
});
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log("connected" + socket.id);
});
I have another project, my client and i want to open a socket connection to the server, but i failed to do so. 我有另一个项目,我的客户端,我想打开与服务器的套接字连接,但是我没有这样做。 all examples i've seen using an index.html file inside the node project (indeed works). 我所看到的所有示例都在节点项目中使用index.html文件(实际上是可行的)。 i tried adding my client: 我尝试添加我的客户:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<div>
<button ng-click="io.connect('http://localhost:8001')">hi</button>
</div>
but i don't get the "connected" log . 但我没有得到“已连接”的日志。
appreciate any help. 感谢您的帮助。
This client should give you a persistent socket connection : 该客户端应为您提供持久的套接字连接:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io.connect(http://localhost:8001);
// attach your events here
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.