22

我正在尝试创建一个虚拟套接字以用于我的一些测试

var net = require("net");

var s = new net.Socket();

s.on("data", function(data) {
  console.log("data received:", data);
});

s.write("hello!");

收到此错误

错误:此套接字已关闭。

我也试过用

var s = new net.Socket({allowHalfOpen: true});

我究竟做错了什么?


作为参考,完整的测试看起来像这样

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
});
4

5 回答 5

39

我不认为服务器进入监听状态。这是我用的..

// 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\n\n');

s.on('data', function(d){
    console.log(d.toString());
});

s.end();
于 2013-09-06T19:06:49.157 回答
6

尝试这个。

生产代码app.js

var net = require("net");

function createSocket(socket){
    var s = socket || new net.Socket();
    s.write("hello!");
}

exports.createSocket = createSocket;

测试代码:test.js:(摩卡)

var sinon = require('sinon'),
    assert = require('assert'),
    net = require('net'),
    prod_code=require('./app.js')

describe('Example Stubbing net.Socket', function () {
    it("should say hello on connect", function (done) {
        var socket = new net.Socket();
        var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {
            console.log(data);
            assert.equal("hello!", data);
            done();
        });
        stub.on = socket.on;
        prod_code.createSocket(socket);
    });
});
于 2013-09-06T19:46:16.077 回答
1

我们可以使用net npm 模块创建套接字服务器并在任何地方进行监听。创建套接字服务器后,我们可以检查使用 telnet(客户端套接字)与服务器交互。

服务器.js

'use strict';

const net = require('net');
const MongoClient= require('mongodb').MongoClient;
const PORT = 5000;
const ADDRESS = '127.0.0.1';
const url = 'mongodb://localhost:27017/gprs';

let server = net.createServer(onClientConnected);
server.listen(PORT, ADDRESS);

function onClientConnected(socket) {
  console.log(`New client: ${socket.remoteAddress}:${socket.remotePort}`);
  socket.destroy();
}

console.log(`Server started at: ${ADDRESS}:${PORT}`);

function onClientConnected(socket) {

  let clientName = `${socket.remoteAddress}:${socket.remotePort}`;
  console.log(`${clientName} connected.`);
  socket.on('data', (data) => {
    let m = data.toString().replace(/[\n\r]*$/, '');
    var d = {msg:{info:m}};
    insertData(d);
    console.log(`${clientName} said: ${m}`);
    socket.write(`We got your message (${m}). Thanks!\n`);
  });

  socket.on('end', () => {
    console.log(`${clientName} disconnected.`);
  });

}

function insertData(data){
  console.log(data,'data');
        MongoClient.connect(url, function(err, db){
        console.log(data);
        db.collection('gprs').save(data.msg , (err,result)=>{
            if(err){
                console.log("not inserted");
            }else {
                console.log("inserted");
            }
        });
    });
}

使用远程登录:

$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
We got your message (hi). Thanks!
于 2018-01-31T03:56:56.373 回答
0

您需要先连接您的套接字,然后才能对其进行写入:

var PORT = 41443;

var net = require("net");

var s = new net.Socket();

s.on("data", function(data) {
  console.log("data received:", data);
});
s.connect(PORT, function(){
    s.write("hello!");
});
于 2014-12-03T22:06:47.470 回答
0

它将对 websocket 有用的代码

'use strict';

const express = require('express');
const { Server } = require('ws');
const bodyParser = require('body-parser');
const  cors = require('cors');

 
const PORT = process.env.PORT || 5555;
const INDEX = '/public/index.html';

const router = express.Router();

var urlencodedParser = bodyParser.urlencoded({ extended: false });

router.get('/', function(req, res) {
    res.sendFile(INDEX, { root: __dirname });
});

const server = express()
  .use(router)
  .use(bodyParser.json())
  .use(cors)
  .listen(PORT, () => {
    console.log(`Listening on ${PORT}`)
  });

const wss = new Server({ server });

wss.on('connection', (ws) => {
    ws.on('message', message => {
        var current = new Date();
      console.log('Received '+ current.toLocaleString()+': '+ message);
      wss.clients.forEach(function(client) {
        client.send(message);

        var getData = JSON.parse(message);
        var newclip = getData.clipboard;
        var newuser = getData.user;

        console.log("User ID : "+ newuser);
        console.log("\nUser clip : "+ newclip);
    });
  });
});

于 2022-01-10T04:48:44.650 回答