Detailed introduction to sockets in Python

零下一度
Release: 2017-07-18 15:23:35
Original
2098 people have browsed it

Socket is usually also called "socket", which is used to describe the IP address and port. It is the handle of a communication chain. Applications usually make requests to the network or respond to network requests through the "socket".

Socket originated from Unix, and one of the basic philosophies of Unix/Linux is "everything is a file". For files, use the [Open] [Read-Write] [Close] mode to operate. Socket is an implementation of this mode. Socket is a special file. Some socket functions are operations on it (read/write IO, open, close)

socket and The difference between file:

The file module is to [open] [read and write] [close] for a specified file

1. socket module

Socket, commonly known as socket, is actually a combination of IP address and port. Similar to this form (ip, port), where ip represents a certain host and port represents an application. We can communicate with another host through socket.

The analysis of the socket source code is in the tarnado series of articles and is currently being written. . . . .

1. Communication method

tcp communication

udp communication

Unix-based communication

2. Socket Method

# 暂时知道的也就这么多,之后要是在用到其他的我会继续进行保存Methods of socket objects (keyword arguments not allowed):
    
    _accept() -- accept connection, returning new socket fd and client address
    bind(addr) -- bind the socket to a local address 给本地地址绑定一个socket套接字
    close() -- close the socket 关闭一个套接字
    connect(addr) -- connect the socket to a remote address     连接到远端主机
    connect_ex(addr) -- connect, return an error code instead of an exception
    dup() -- return a new socket fd duplicated from fileno()
    fileno() -- return underlying file descriptor
    getpeername() -- return remote address [*]
    getsockname() -- return local address
    getsockopt(level, optname[, buflen]) -- get socket options
    gettimeout() -- return timeout or None
    listen([n]) -- start listening for incoming connections
    recv(buflen[, flags]) -- receive data   接受数据
    recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)    接受数据到缓冲区中,
    recvfrom(buflen[, flags]) -- receive data and sender's address    recvfrom_into(buffer[, nbytes, [, flags])      -- receive data and sender's address (into a buffer)sendall(data[, flags]) -- send all data 发送数据给远端主机,3.x之后只能发送字节形式,因此在发送的时候一般要进行转换bytes
    send(data[, flags]) -- send data, may not send all of it 也是发送数据,区别在于send发送的不完整,随机进行发送的,二sendall发送的完整
    sendto(data[, flags], addr) -- send data to a given address 基于udp发送数据的
    setblocking(0 | 1) -- set or clear the blocking I/O flag    是否设置成阻塞模式0 代表阻塞,1代表非阻塞
    setsockopt(level, optname, value) -- set socket options     设置一些socket的桉树
    settimeout(None | float) -- set or clear the timeout    设置超时市场
    shutdown(how) -- shut down traffic in one or both directions    
    if_nameindex() -- return all network interface indices and names
    if_nametoindex(name) -- return the corresponding interface index
    if_indextoname(index) -- return the corresponding interface name
 
     [*] not available on all platforms!
Copy after login

2. Simple chat robot

If you send a data, the server will reply to him with a data + Hello

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/3 4  5 import socket 6 # 创建一个server对象 7 server_obj = socket.socket() 8 # 绑定一下端口 9 server_obj.bind(("127.0.0.1", 8888, ))10 # 设置监听的等待队列长度为5,当大于5的时候就拒绝连接11 server_obj.listen(5)12 13 while True:14     # 等待接受客户端的连接,为阻塞方式15     conn, address = server_obj.accept()16     # 发送欢迎信息17     conn.sendall(bytes("欢迎来到简单的聊天室..", encoding='utf-8'))18     while True:19         # 接受到对面的消息就会把对面消息后面加上你好重新发送回去20         ret = str(conn.recv(1024), encoding='utf-8')21         if ret == 'q':22             # 如果对面发送的为q就退出23             break24         conn.sendall(bytes(ret + ",你好", encoding='utf-8'))
Copy after login
server
##
# -*- coding:utf-8 -*-# zhou# 2017/7/3import socket

client = socket.socket()
client.connect(("127.0.0.1", 8888, ))# 接受欢迎信息并打印ret = str(client.recv(1024), encoding='utf-8')print(ret)while True:
    message = input("请输入您要发送的内容:")
    client.sendall(bytes(message, encoding='utf-8'))if message == 'q':breakret = str(client.recv(1024), encoding='utf-8')print(ret)
Copy after login
client

3. Simple ftp upload

Implemented uploading a picture to the server

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/2 4  5 import socket 6  7 server = socket.socket() 8 server.bind(("127.0.0.1", 9998, ))  # 绑定ip 9 server.listen(5)10 11 while True:12     conn, address = server.accept()13     # 连接之后首先接收文件大小14     file_size = int(str(conn.recv(1024), encoding='utf-8'))15     # 用来解决粘包问题的16     conn.sendall(bytes("1001", encoding='utf-8'))17     # 已经接受的文件大小18     has_size = 019     num = 120     # 连接之后接收文件21     f = open("new.jpg", 'wb')22     while True:23         num += 124         if file_size == has_size:25             break26         data = conn.recv(1024)27         f.write(data)28         has_size += len(data)29     f.close()   # 关闭文件
Copy after login
ftpserver

##
 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/2 4  5  6 import os 7 import socket 8  9 client = socket.socket()10 11 client.connect(("127.0.0.1", 9998), )12 # 传送文件大小13 file_size = os.stat("1.jpg").st_size14 print(file_size)15 # 发送文件大小16 client.sendall(bytes(str(file_size), encoding='utf-8'))17 client.recv(1024)   # 解决粘包问题18 # 发送文件19 with open("1.jpg", 'rb') as f:20     for line in f:21         client.sendall(line)22 client.close()
Copy after login
ftpclient

Four. Sticky Solution to package problem

Regarding the description of the third ftp upload above,

To solve the problem of sticky package, when we upload a file, first upload its size. When we upload After the size is determined, an acceptance statement must be written, and the server must immediately send us a piece of data for confirmation after receiving the file size, so that we can perfectly separate the data by size.

 

The above is the detailed content of Detailed introduction to sockets in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!