我能用javascript连接到本地主机python服务器吗?

2024-03-29 12:45:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试做一个chrome扩展,它可以将当前访问页面的url发送到另一台机器上运行的python服务器。我对javascript非常陌生,但是还没有找到任何与sockets、python和jvascript相关的东西。在

python服务器的代码:

import socket
import sys
from _thread import *
import webbrowser

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ""
port = 9999

try:
    s.bind((host,port))
except socket.error as e:
    print (str(e))

s.listen(5)

def threaded_client(conn):
conn.send(str.encode("Message recieved \n"))

while True:
    reply = ""
    data = conn.recv(2048)
    b = str(data)
    link = b[2:-1]
    #if data == "":
    conn.send(str.encode("\n hi\n"))
    webbrowser.open(link)
    if not data:
        break
    conn.sendall(str.encode(reply))
    print (data)
    print (link)
conn.close()

while True:
    conn, addr = s.accept()
    print("connected to:" +addr[0]+":"+str(addr[1]))
    start_new_thread(threaded_client,(conn,))

我不知道我的客户机代码有多有用,因为我还没有设法在客户机和服务器之间建立连接。在

javascript客户端代码: html位:

^{pr2}$

javascript位:

$('#sendy').bind('click', sendAMessage());

function sendAMessage(msg) {
  var c = net.createConnection(9999, '192.168.2.105');
  c.on("connect", function() {
    // connected to TCP server.
    c.write(msg);
  });
}

}

再次重申,我对javascript和chrome扩展非常陌生,任何帮助都是值得感谢的。目前我最关心的是在客户机和服务器之间建立连接。剩下的我希望能弄清楚。在


Tags: 代码import服务器data客户机linksocketjavascript