1, the principles outlined socket
Also known word or jack socket Suite is an essential tool for network communication. There is a saying: "No socket, not the network." Since the first socket used on BSD Unix, and Unix / Linux regarded as a classic of the supreme philosophy is "Everything is a file." Therefore, when using the socket is completely in line with this philosophy, it relates to listen (), bind (), accept (), the function function write () / read (), close () is similar to other basic file operations.
Following substantially as a function of the client and server required enumerated in detail
Both figures above overview of the communication principle of socket
2, python socket server in Examples
Server:
# 导入 socket模块
import socket
import urllib.request
# 创建 socket 对象
s = socket.socket()
# 绑定IP地址和端口号
s.bind(("10.202.98.14", 8000)) #本主机地址和端口号
# 设置最大连接数,超过后排队
s.listen(5)
print("等待连接...")
while True:
conn,addr = s.accept() #conn为套接字,addr为Ip地址
print("连接地址: " ,addr)
msg='欢迎访问菜鸟教程!'
conn.sendall(msg.encode('utf-8')) #向客户端发送消息,8位编码格式编码为字节传输
urlByte = conn.recv(1024) #接收客户端的消息
print(urlByte) #接收到的是字节类型
print(urlByte.decode('utf-8'))#对字节进行解码
urlStr = urlByte.decode('utf-8')
urllib.request.urlretrieve(urlStr,"1.jpg") #给了图片网址链接,将图片下载下来
conn.close()#关闭套接字
Client:
# 导入 socket模块
import socket
import urllib.request
# 创建 socket 对象
s = socket.socket()
# 连接服务,指定IP地址和端口(服务器端的)
s.connect(("10.202.98.14", 8000))
#向服务端发送图片网址链接,编码成字节形式进行发送
s.sendall("http://img.netbian.com/file/20110706/527402dc667609f7ad644c5a51361fdc.jpg".encode('utf-8'))
# 接收小于 1024 字节的数据
msg = s.recv(1024)#接收服务端的消息,接收的是字节类型
s.close()
print (msg.decode('utf-8'))#对字节类型进行解码
First implementation of the server, the server to accept the implementation of the start blocks, waiting for response from the client, and then perform a client.
Client The results:
Server implementation of the results: the picture and download the
Reference: socket technology explain (see socket programming)