Andres Guevara
Andres Guevara

Reputation: 1

Local socket connection between a Python program and JS

I'm trying to establish a socket connection between Python (Client) and JavaScript (Server), but I'm a little bit confused how to do it.

On the serverside in javascript I have this code:

JS Server

var net = require('net');

var server = net.createServer(function(socket){
        socket.write('Echo server\r\n');
        socket.pipe(socket);
});

server.listen(1337, '127.0.0.1');

And for the client side on Python I have this

Python Client

import socket

class JavaSocket:

def __init__(self):
    self.client_socket = None
    self.portNumber = 1337

def socketMethod(self):
    """ This method will establish the socket Connection between Java and Python """
    try:
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.connect(("localhost",self.portNumber))
        print(self.portNumber)
    except Exception as e:
        raise

def socketConnection(self):

    sentence = "Test"
    self.client_socket.send(sentence.encode())
    data = self.client_socket.recv(1024)
    print(data)
    if data is not None:
        print("Socket closed")
    self.client_socket.close()


js = JavaSocket()
js.socketMethod()
js.socketConnection()

I'm not really familiar with JS and socket connections. I tried running this in Python and got an error indicating that the connection was refused.

Upvotes: 0

Views: 412

Answers (1)

Andres Guevara
Andres Guevara

Reputation: 1

The code for the client server side that I worked for me was

var net = require('net');
var server = net.createServer(function(socket){
    socket.write('Echo server\r\n');
    socket.pipe(socket);
    socket.on('data', function(buffer)
        {
             console.log(buffer.toString());
         }
    });

server.listen(1337, '127.0.0.1');

This would connect to the client and send the "Echo server" message and print the message "Test" from the client

Upvotes: 0

Related Questions