如何在 node.js 中创建一个简单的套接字? [英] How to create a simple socket in node.js?
本文介绍了如何在 node.js 中创建一个简单的套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个虚拟套接字以用于我的一些测试
I'm trying to create a dummy socket for use in some of my tests
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.write("hello!");
出现此错误
错误:此套接字已关闭.
Error: This socket is closed.
我也试过用
var s = new net.Socket({allowHalfOpen: true});
我做错了什么?
作为参考,完整的测试如下
For reference, the complete test looks like this
it("should say hello on connect", function(done) {
var socket = new net.Socket();
var client = Client.createClient({socket: socket});
socket.on("data", function(data){
assert.equal("hello", data);
done();
});
client.connect();
// writes "hello" to the socket
});
推荐答案
我不认为服务器处于监听状态.这是我用的..
I don't think the server is put into listening state. This what I use..
// server
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
})
.listen(8080);
// client
var s = require('net').Socket();
s.connect(8080);
s.write('Hello');
s.end();
仅限客户端..
var s = require('net').Socket();
s.connect(80, 'google.com');
s.write('GET http://www.google.com/ HTTP/1.1
');
s.on('data', function(d){
console.log(d.toString());
});
s.end();
这篇关于如何在 node.js 中创建一个简单的套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文