Skip to main content
 首页 » 编程设计

连接到使用 Nodejs 创建的 socket.io 服务器的 Python 脚本

2025年05月04日35傻小

我在 http://localhost:8090 托管了一个 HTTP 服务器使用 nodejs。

app.js 文件

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); 
        });         
    }); 
}); 

现在我写了一个 python 脚本来使用套接字编程连接到这个服务器。

client.py文件

#!/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     

当我运行 client.py 文件时,我无法在服务器端收到“感谢连接”消息。

我无法理解我哪里出错了。

请您参考如下方法:

Socket.io 使用创建 WebSocket 服务器。在 python 客户端中,您通过原始套接字发送纯文本。你需要的是socket.io client library for python .