如何使用python套接字从html获取输入 [英] how to get input from html using python socket

查看:72
本文介绍了如何使用python套接字从html获取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码可以在localhost上启动一个简单的套接字服务器.但是,我希望通过浏览器访问它时显示一个html页面.html将包含两个文本字段和提交按钮.当用户在文本字段中输入文本并单击提交"按钮时,我希望程序从文本字段中读取.我该怎么办?

解决方案

您的问题的即时答案(希望如此)位于最后一部分 答案-,如果我对您的问题的解释有误,请在评论部分告诉我..


混乱-您正在混淆基本知识-要显示html页面,您只需要服务器(在您的情况下为localhost),浏览器将使用 HTTP / HTTPS 协议以获取该内容/响应/html页面.在Python中(其他语言几乎相同),访问网络服务有两个级别:

  • 通过 sockets 进行低级别访问.
  • 通过应用程序级网络协议(例如 HTTP FTP 等)的更高级别.

套接字-用简单的英语来说,它是机器操作系统提供的一种功能(接口),用于实现客户端和服务器(用于高级网络协议),例如进程之间的通信.这些进程可以在同一台计算机上运行,​​也可以在物理上分开的计算机上运行(例如,使用浏览器请求网站).

典型的套接字客户端是(从浏览器中请求所需的html):

  client_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)client_sock.connect((" localhost,80)) 

但是要使其正常工作,您必须已经在服务器上运行(将为html提供服务):

  server_sock = socket.socket()#创建一个套接字对象server_sock.bind((localhost,80))#绑定到端口server_sock.listen(5)而True:#行用于我们希望服务器执行的任何操作 

server_sock.bind((localhost,80))已将localhost:80(套接字基本上是'host_name:port_number')绑定(分配/分配了)此 server_sock,即对 localhost:80 的任何调用/请求都将按照上面中的行进行处理,而上面代码的True:块可以是文本响应,HTML等.


典型的网络场景-我们输入一个网站名称​​ www.google.com (通过 DNS 协议解析为IP-另一个故事),然后按Enter键,我们会得到Google的搜索主页作为响应-这是您的客户,即输入网站名称,然后按Enter键在技术上是 client_sock.connect('www.google.com',80),它之所以起作用,是因为在另一台(远程)机器/系统/主机上,它们绑定了 server_socket 并正在监听,即

  server_sock.bind('machine's_IP',80)server_sock.listen(5)而True:#接受来自外部的连接(client_socket,地址)= server_socket.accept()#这是将我们发送回Google的行#homepage html作为对我们Web请求的响应. 


总而言之,可以使用(几乎)任何编程语言来实现服务器(在您的情况下为Web服务器),例如python或C等,但是最底层,即最底层,确切地说是数据在2个进程之间传递的位置,无论是在同一计算机上使用 locahost (环​​回)还是在物理上分开的计算机/主机上运行的每个进程(典型的网络场景)通过 HTTP ( TCP )协议位于套接字上.套接字是基本组成部分 HTTP HTTPS FTP SMTP 协议(所有这些都是TCP类型的协议)已定义.

DNS DHCP VOIP 协议是 UDP 协议,但它们也建立在套接字之上.


答案-首先,创建一个web_server.py并粘贴以下代码(仅查看其工作原理)并以脚本形式运行该文件,即从文件的位置运行"python

web_server.py"在命令提示符/终端:

 #!/usr/bin/env python进口插座主机='本地主机'端口= 80server_sock = socket.socket(socket.AF_INET,\socket.SOCK_STREAM)#创建一个套接字对象server_sock.bind((host,port))#绑定到端口打印正在启动服务器",主机,端口打印为此的Web服务器URL将为http://%s:%d/"%(主机,端口)server_sock.listen(5)#现在等待客户端连接.打印进入无限循环;按CTRL-C退出'而True:#与客户端建立连接.client_sock,(client_host,client_port)= socket.socket.accept()打印来自的连接",client_host,client_portclient_sock.recv(1000)#应该从客户端接收请求.(得到 ....)client_sock.send('HTTP/1.0 200 OK \ n')client_sock.send('Content-Type:text/html \ n')client_sock.send('\ n')#标头和正文应由其他换行符分隔#您可以在< body>中将您的2个文本字段html粘贴到此处.client_sock.send("< html>< body>< h1> Hello World</h1>这是我的服务器!</body></html>")client_sock.close() 


PS .您必须实现HTTP服务器(网络服务器)-肯定会在最低级别(即

)使用套接字接口

  server_sock.bindserver_sock.listenserver_sock.accept 

I have a code to start a simple socket sever on localhost. However, I want it to display a html page when it is accessed through browser. The html will contain two text fields and submit button. When user enters text in text fields and clicks on submit button, I want the program to read from text fields. How Can I Do That?

解决方案

The instant answer (I hope so) to your question is in the last section The Answer - and, if I have interpreted your question wrong, let me know in the comment section.


The confusion - You are confusing the fundamentals - to display a html page, you simply need a server (localhost in your case), and the browser will use the HTTP/HTTPS protocol to fetch that content/response/html page. In Python (almost same for other languages) there are two levels of access to network services:

  • Low-level via sockets.
  • Higher-level via application level network protocols, like HTTP, FTP, etc.

Sockets - in plain english it is a functionality (interface) provided by the machine's operating system to implement client and server (for the higher-level network protocols) like communication between the processes. These processes can be running on a same machine or both processes on physically apart machines (e.g. requesting a website using browser).

A typical socket client is (asking for the desired html from browser):

client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.connect(("localhost", 80))

But to make it work you must already have server running (which will serve the html):

server_sock = socket.socket()     # Create a socket object
server_sock.bind((localhost, 80)) # Bind to the port
server_sock.listen(5) 
while True:
     # lines for whatever we want server to do  

The line server_sock.bind((localhost, 80)) has binded (assigned/allocated) the localhost:80 (a socket is basically 'host_name:port_number') to this server_sock i.e. any call/request to localhost:80 will be handled as per the lines in the above while True: block of the code above, can be a text response, HTML, etc.


Typical web scenario - We enter a website name www.google.com (which is resolved into an IP via DNS protocol - a whole another story) and hit enter, we'll get the Google's search homepage in response - Here you're the client, that is entering the website name and hitting enter is technically client_sock.connect('www.google.com', 80), and it only worked because on another (remote) machine/system/host they have server_socket binded and listening i.e.

server_sock.bind('machine's_IP', 80)
server_sock.listen(5)
while True:
    #accept connections from outside
    (client_socket, address) = server_socket.accept()

    # here will be the lines which send us back the Google's 
    # homepage html as a response to our web request.


To sum-up, servers (webserver in your case) can be implemented using (almost) any programming languages e.g. python or C, etc, but the basis, the lowest layer, exactly where the data is passed between 2 processes whether on the same machine using locahost (loopback) or each process running on physically apart machine/host (typical web scenario ) via the HTTP (TCP) protocol rest upon sockets. Sockets are the fundamental building block from which HTTP, HTTPS, FTP, SMTP protocols (all of these are TCP-type protocols) are defined.

DNS, DHCP, VOIP protocols are UDP protocols but they too are built on top of sockets.


The Answer - To start, create a web_server.py and paste the following code (only to see how it works) and run the file as script i.e. from the file's location run "python

web_server.py" in command prompt/terminal:

#!/usr/bin/env python
import socket

host = 'localhost'
port = 80
server_sock = socket.socket(socket.AF_INET,\
                            socket.SOCK_STREAM)    # Create a socket object
server_sock.bind((host , port))                    # Bind to the port

print 'Starting server on', host, port
print 'The Web server URL for this would be http://%s:%d/' % (host, port)

server_sock.listen(5)             # Now wait for client connection.

print 'Entering infinite loop; hit CTRL-C to exit'
while True:
    # Establish connection with client.    
    client_sock, (client_host, client_port) = socket.socket.accept()
    print 'Got connection from', client_host, client_port
    client_sock.recv(1000) # should receive request from client. (GET ....)
    client_sock.send('HTTP/1.0 200 OK\n')
    client_sock.send('Content-Type: text/html\n')
    client_sock.send('\n') # header and body should be separated by additional newline
    # you can paste your 2 text field html here in the <body>
    client_sock.send("""
        <html>
        <body>
        <h1>Hello World</h1> this is my server!
        </body>
        </html>
    """) 
    client_sock.close()


P.S. You have to implement a HTTP server (webserver) - which will definitely use the socket interface at the lowest level i.e.

server_sock.bind
server_sock.listen
server_sock.accept 

这篇关于如何使用python套接字从html获取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆