Mohit Agarwal
Mohit Agarwal

Reputation: 145

Python script to connect to socket.io Server created using Nodejs

I hosted a HTTP server at http://localhost:8090 using nodejs.

app.js file

var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');

var server = http.createServer(function(req, res) {
        res.writeHead(200, { 'Content-type': 'text/html'});
        res.end(fs.readFileSync(__dirname + '/index.html'));
        }).listen(8090, function() {
            console.log('Listening at: http://localhost:8090');
            });

socketio.listen(server).on('connection', function (socket) {

        socket.on('message', function (msg) {
        console.log('Message Received: ', msg);
        socket.broadcast.emit('message', msg);
        });        
    });
});

Now I write a python script to connect to this server using socket programming.

client.py file

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = '127.0.0.1'     # Get local machine name
port = 8090                # Reserve a port for your service.

s.connect((host, port))
s.send('Thanks for connecting.')
s.close    

When I run the client.py file, I'm unable to receive the 'Thanks for connecting' message at the server side.

I'm unable to understand where I'm going wrong.

Upvotes: 2

Views: 4071

Answers (1)

Scorpil
Scorpil

Reputation: 1526

Socket.io uses creates WebSocket server. In python client you are sending plain text through raw socket. What you need is socket.io client library for python.

Upvotes: 1

Related Questions