4

The below code works fine if I run it from my command line, but if I run this code anywhere in my project I get this error:

net.Socket is not a constructor

I've tried making the below code an object and importing / requiring it into my project and I still get that error.

var net = require('net');

var client = new net.Socket();
    client.connect(3000, '127.0.0.1', function() {
    console.log('Connected');
    client.write('Hello, server! Love, Client.');
});

Am I miss understanding what require does, I also tried using import and import * as to obtain 'net'.

I'm not too sure what information would be useful in the situation. Any suggestions would be great.

2
  • Are you running this code via node or browser? If from node, what version of node (node -v)? Commented Nov 14, 2016 at 22:59
  • It works fine if I run in via node, e.g. node test.js (it works), if I run it via my browser I get net.createConnection is not a constructor or net.Socket is not a constructor. Node version 4.4.5 Commented Nov 14, 2016 at 23:04

2 Answers 2

9

There are no plain TCP sockets in the browser, so that is why trying to use net.Socket in the browser (via webpack, browserify, etc.) won't work.

There could be a "polyfill" of sorts that requires a server to make the TCP connection on the browser's behalf though (or perhaps via some bridge to a Flash or Java applet).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I'll look into implementing polyfill to get it working.
@AdamEdney : Hi adam, I am getting the same issue, any updates in this
@Krishna I decided to use a websocket. i.e. npmjs.com/package/websocket. Hope this helps!
@AdamEdney : Are you able to connect to any TCP server using websocket or is it only work with the websocket server.
@javadeveloper To be honest I'm no expert, I have only tested it with a server that has web socket server.
0

use node 16 version. these features are currently under Node.js v16.9.1 https://nodejs.org/dist/latest-v16.x/docs/api/net.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.