2011-06-09 49 views
0

你怎么能提取从邮件的NodeJS弦?具体而言,我正在修改一个简单的聊天室示例以接受来自客户端的特定命令字符串的NodeJS

例子:

sock.on('connection', function(client){ 
    var s = the string in client.message... 
    if(s == "specific string"){ 
     //do this 
    } 
    else{ 
     //do that 
    } 
}); 

我是新来的NodeJS和文档一直到目前为止非常有帮助。如果我正在接近这种错误的方式,我一定会喜欢其他解决方案。谢谢。

编辑1:服务器初始化

serv = http.createServer(function(req, res){ 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    // read index.html and send it to the client 
    var output = fs.readFileSync('./index.html', 'utf8'); 
    res.end(output); 
}); 
// run on port 8080 
serv.listen(8080); 

编辑3:我知道,我还没有足够具体的,对不起。以下是显示我正在遵循的教程的链接:http://spechal.com/2011/03/19/super-simple-node-js-chatroom/

具体来说,我想创建教程(我已经能够做到)提供的聊天室,然后检查人正在广播给对方看它们是否包含特定字符串的邮件。

例如,如果聊天室中的客户端提交了字符串“alpha”(类型为alpha,按Enter),则该字符串将被广播给所有其他客户端,并且服务器将通过广播字符串“Alpha has been收到“。给所有的客户。我确切的问题(据我所知)是我不能做任何形式的字符串比较我的事件侦听器收到的消息。是否可以从他们的消息中提取我的聊天室成员输入的文本?

回答

3

哪里是你的 'sock.on(' 数据 '函数(数据){})' 处理? 我认为HTTP例子实际上是你在找什么,下面列出。

举例(TCP服务器):

var server = net.Server(function(socket) { 
    socket.setEncoding('ascii'); 

    socket.on('data', function(data) { 
    // do something with data 
    }); 

    socket.on('end', function() { 
    // socket disconnected, cleanup 
    }); 

    socket.on('error', function(exception) { 
    // do something with exception 
    }); 
}); 
server.listen(4000); 

举例HTTP服务器:

var http = require('http'); 
var url = require('url'); 
var fs = require('fs'); 

var server = http.createServer(function (req, res) { 

    // I am assuming you will be processing a GET request 
    // in this example. Otherwise, a POST request would 
    // require more work since you'd have to look at the 
    // request body data. 

    // Parse the URL, specifically looking at the 
    // query string for a parameter called 'cmd' 
    // Example: '/chat?cmd=index' 
    var url_args = url.parse(req.url, true); 

    // Should have error checking here... 
    var cmd = url_args.query.cmd; 

    res.writeHead(200, {'Content-Type': 'text/html'}); 

    var output; 
    if (cmd == "index") { 
    // read index.html and send it to the client 
    output = fs.readFileSync('./index.html', 'utf8'); 
    } else if (cmd.length > 0) { 
    output = "cmd was not recognized."; 
    } else { 
    output = "cmd was not specified in the query string."; 
    } 
    res.end(output); 
}); 

server.listen(8080); 
+0

我为我的无知抱歉,但我不太清楚你的问我。我会发布我相信*你在编辑中要求我的内容。 – viperld002 2011-06-09 19:18:17

+0

哦,我想我现在得到你的要求。是的,我的处理程序函数位于我的服务器初始化代码之外和之后。它正好在serv.listen()行之后。 – viperld002 2011-06-09 19:36:21

+0

呀,文档可以得到一个有点混乱,有时。希望这个HTTP例子实际上就是你想要的。 Node.JS网站上的聊天示例非常复杂,但源代码看似可读。在这个例子中他们使用HTTP服务器。 https://github.com/ry/node_chat – 2011-06-09 20:10:40