0
votes

I'm trying to combine a Node.js with Python to create a socket connection.

The problem is that I can send data, but I can't maintain the connection.

This is my server in Node.js

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 1337;

net.createServer(function(sock) {

    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    sock.on('data', function(data) {

        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write('You said "' + data + '"');

    });

    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

and this is my client side in Python

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 1337)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

try:

    # Send data
    message = 'This is the message.'
    print >>sys.stderr, 'sending "%s"' % message
    sock.sendall(message)

finally:
    print >>sys.stderr, 'closing socket'

This works great but the client disconnects right after it has sent the data.

Ultimately, I want to be able to give user-input to send data, and also receive data.

Any suggestions on how to do this would be appreciated.

1

1 Answers

0
votes

I'll approach the user input scenario. As of now, your program simply runs its course and exists.

You want to be able to combine two naively blocking operations, running some sort of input loop (e.g. while True: data = input()) but handle incoming traffic as well.

The basic way to do this is to have 2 threads, one for user input and the other for socket connections in similar while True: data = socket.recv(buff) loop, but there's another catch here as you might block on a single connection -- you'll have to dedicate a thread per connection. In order to avoid this, you could use select, which maintains socket connections for you asynchronously.

If there's no user-input, than you can just use select -- that will be sufficient to handle multiple connections in a concise manner.

Either way, I suggest you take a look at some asynchronous event-driven frameworks that are select based such as asyncio and Twisted.