John Mellow
John Mellow

Reputation: 131

node js http createServer socket

The doubt with with code is two things:

  1. When i send request through a browser, i dont get a console log message as "connected" but if i use http.get() or http.request() , it works fine 2)The "connect" event receives a callback with req,clientSocke,head ! now where can i see the server socket ?

    const http=require("http")
    
    const server=http.createServer()
    server.on("connect",(req,c_socket,head)=>{
    
     console.log("connected")
    
    })
    server.listen(5000,()=>{console.log("server up)})
    

Upvotes: 1

Views: 954

Answers (1)

galih wisnuaji
galih wisnuaji

Reputation: 153

  1. when you access the server via browser, the method is using GET not CONNECT. That's why console.log does not show. if you want console.log to show when accessing from the browser, you can use request event.

this is an explanation from node.js docs.

'connect' event is emitted each time a server responds to a request with a CONNECT method. If this event is not being listened for, clients receiving a CONNECT method will have their connections closed. node.js docs

  1. you can make a socket server with a net package with createSever method. this is an example of how to make a simple request to the socket server.
const http = require('http');
const net = require('net');
const { URL } = require('url');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('hello world');
});

server.on('connect', (req, clientSocket, head) => {
  console.log('connected');
  // Connect to an origin server
  const { port, hostname } = new URL(`http://${req.url}`);
  const serverSocket = net.connect(port || 80, hostname, () => {
    clientSocket.write(
      'HTTP/1.1 200 Connection Established\r\n' +
        'Proxy-agent: Node.js-Proxy\r\n' +
        '\r\n'
    );
    serverSocket.write(head);
    serverSocket.pipe(clientSocket);
    clientSocket.pipe(serverSocket);
  });
});

server.listen(5000, () => {
  console.log('server up');
});

// Make a request to a tunneling server
const req = http
  .request({
    port: 5000,
    host: 'localhost',
    method: 'CONNECT',
    path: 'www.google.com:80',
  })
  .end();

req.on('connect', (res, socket, head) => {
  console.log('got connected!');

  // Make a request over an HTTP tunnel
  socket.write(
    'GET / HTTP/1.1\r\n' +
      'Host: www.google.com:80\r\n' +
      'Connection: close\r\n' +
      '\r\n'
  );
  socket.on('data', (chunk) => {
    console.log(chunk.toString());
  });
  socket.on('end', () => {
    console.log('end');
  });
});

Upvotes: 3

Related Questions