如何使用Express post请求发出Socket.io或Sockjs?

use*_*217 6 node.js express socket.io samsung-smart-tv

我知道这个问题有点尴尬,但问题来自三星电视2010/2011年SmartTV(和蓝光播放器;当然2012年模拟器工作正常).我将简单的聊天示例从源和包移植到SmartTV应用程序.它们都回归到JSONP轮询,但是从SmartTV应用程序只能发射/推送到服务器一次.从服务器接收消息可能多次没有任何问题.在三星D论坛寻找答案后(当然没有),我认为解决这个问题的最快方法是部署一个Express服务器,获取post数据和JSON.parse,然后在内部发出Socket.io/Sockjs在服务器本身内部.

有人能告诉我一个简单的示例代码,所以我可以从那里开始吗?非常感谢.

我快速编写代码,但似乎不起作用:

LIB/server.js

var express = require('express')
  , app = express.createServer()
  , io = require('socket.io').listen(app);

app.listen(80);

app.use(express.bodyParser());

app.get('/', function (req, res) {
  res.sendfile('/var/www/mpgs_lite_v3/index.html');
});

app.post('/', function(req, res){
  console.log(req.body);
  io.sockets.emit('my other event', req.body);
  res.redirect('back');
});

io.sockets.on('connection', function (socket) {
  //socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
Run Code Online (Sandbox Code Playgroud)

的index.html

<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
</head>
<body>
<form method="post" action="/">
     <input type="hidden" name="_method" value="put" />
     <input type="text" name="user[name]" />
     <input type="text" name="user[email]" />
     <input type="submit" value="Submit" />
 </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

"我的其他事件"似乎没有收到任何东西.

Lin*_*iel 12

更新:我为您更新了示例,使其更加完整.我之前没有app.listen,这里也是一个客户端脚本,它表明它确实工作正常:

<!doctype html>
<html>
    <head>
        <script src="//www.google.com/jsapi"></script>
        <script src="/socket.io/socket.io.js"></script>
        <script>google.load("jquery", "1.7.1")</script>
        <script>
            var socket = io.connect("localhost", {port: 3000});
            socket.on("foo", function(message) { console.log("foo: ", message) });
            $(function() {
                $("button").click(function() {
                    $.post("/foo", { message: $("input").val() });
                });
            });
        </script>
    </head>
    <body>
        <input type=text>A message</input>
        <button>Click me!</button>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

和服务器,现在有一个app.listen指令:

var express = require("express"),
    app = express.createServer(),
    io = require("socket.io").listen(app)
    index = require("fs").readFileSync(__dirname + "/index.html", "utf8");

app.use(express.bodyParser());

app.get("/", function(req, res, next) {
    res.send(index);
});

app.post("/foo", function(req, res, next) {
    io.sockets.emit("foo", req.body);
    res.send({});
});

app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

用法:

node app.js
Run Code Online (Sandbox Code Playgroud)

导航到http://localhost:3000/并单击按钮.检查控制台输出.