如何使用套接字将信息从 javascript 发送到 python

我想使用套接字将信息从我的 Node.js 代码发送到 Python。我怎样才能做到这一点?

在伪代码中,我想要的是:

js:

sendInformation(information)

Python:

recieveInformation()
sendNewInformation()

js:

recievNewInformation()


哆啦的时光机
浏览 113回答 1
1回答

慕的地8271018

您应该确定哪个代码是服务器,哪个代码是客户端。我假设您的 Python 代码是您的服务器。您可以使用以下命令在 python 中运行服务器:import socketHOST = '0.0.0.0'PORT = 9999    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:    s.bind((HOST, PORT))    s.listen()    conn, addr = s.accept()    with conn:        print('Connected by', addr)        while True:            data = conn.recv(1024)            if not data:                break            conn.sendall(data)然后你可以将你的 Nodejs 客户端代码连接到服务器:var net = require('net');var HOST = '127.0.0.1';var PORT = 9999;var client = new net.Socket();client.connect(PORT, HOST, function() {  console.log('CONNECTED TO: ' + HOST + ':' + PORT);  // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client client.write('Message from client');});// Add a 'data' event handler for the client socket// data is what the server sent to this socketclient.on('data', function(data) {  console.log('DATA: ' + data);  // Close the client socket completely  client.destroy();});// Add a 'close' event handler for the client socketclient.on('close', function() {  console.log('Connection closed');});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python