从这里开始脱离低级趣味
In this chapter, we will leave lower-level electronics aside for a moment, and start talking a little bit about network programming. Since our target is basically a headless system (in this case, a system with no direct output device), we will need some way of interfacing with it.
creating a platform-independent remote access
创建无关平台的远程访问过程
关键问题:
1、TCP/IP socket
2、创建一个用于检索页面的socket应用
3、实现服务器和客户端应用程序,可以通过TCP / IP套接字进行通信。
套接字科普:
您可以将套接字视为双向通信管道。套接字是两种软件模块之间的主要通信方式,尤其在一个网络上。
在操作系统层面上,还有其他更有效的方法,比如:进程间的通信(进程间通信)。
但当通信需要在不同的机器之间建立,甚至可能不同的平台,套接字几乎是唯一的选择。
Sockets can be divided into two parts, a client socket and a server socket. The main
differences are as follows:
套接字实验
1、添加套接字相关库
import socket #For access to socket communication
import sys #To terminate with error code
2、创建INET流套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
参数一:AF_INET协议 参数二:socket.sock_stream 是socket类型
3、IP地址连接WEB服务器,使用gethostbyname()方法、解析IP地址如下代码:
host = "www.beagleboard.org" #The address we will connect to port = 80 #The default port for web-server print "Connecting to %s" % host
# Use socket library to retrieve ip address for www.beagleboard.org try: target_ip = socket.gethostbyname( host )
4、连接sever
client_socket.connect((target_ip , 80))
5、向服务器发送消息
# Send a simple HTTP-GET message msg = "GET / HTTP/1.0\r\n\r\n" client_socket.sendall(msg) except Exception, err: print "Socket connection has failed:" print err sys.exit(2)
6、读取服务器返回的reply
# Ask the socket to retrieve the first 1024 bytes reply = client_socket.recv(1024) print reply client_socket.close() # Close the socket afterwards
成功!