Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: How can I create a fake tcp socket for testing servers

I'm trying to unit test my server code (non-http, custom protocol). I need to create a mock duplex socket that I can send messages to asynchronously and receive messages from.

I've had some marginal success creating a duplex stream from event-stream readArray and writeArray, but readArray requires having the data up front, and writeArray doesn't fire until the stream ends. I need to test over time. An ideal solution would be two duplex sockets linked together.

Are there any existing solutions for this? I'd rather not have to resort to initializing an actual server to test this.

like image 427
ChiperSoft Avatar asked Apr 09 '15 15:04

ChiperSoft


People also ask

How do I test a TCP socket?

On a Windows computerPress the Windows key + R, then type "cmd.exe" and click OK. Enter "telnet + IP address or hostname + port number" (e.g., telnet www.example.com 1723 or telnet 10.17. xxx. xxx 5000) to run the telnet command in Command Prompt and test the TCP port status.

Which module used to create TCP server in node JS?

The node:net module provides an asynchronous network API for creating stream-based TCP or IPC servers ( net. createServer() ) and clients ( net. createConnection() ).

How do I create a TCP server?

On the Program Navigation tree, click PLC Communications>Physical>CPU Ethernet>TCP Servers. Click Add New. Define a port: click the fields to name the server, assign a port, set the Number of Connections, and check Keep Alive.


1 Answers

Node Mitm can actually do that just fine. It can intercept and mock not only HTTP but any TCP connection.

mitm.on("connection", function(socket) { socket.write("Hello back!") })

var socket = Net.connect(22, "example.org")
socket.write("Hello!")
socket.setEncoding("utf8")
socket.read() // => "Hello back!"
like image 133
Tristan Foureur Avatar answered Oct 13 '22 09:10

Tristan Foureur