python socket network programming

Python provides two basic socket modules:

  The first is Socket, which provides the standard BSD Sockets API.

  The second is SocketServer, which provides server-centric classes that simplify the development of web servers.

The following is the Socket module function

1. Socket type

Socket format:

socket(family,type[,protocal]) Create a socket with the given address family, socket type, and protocol number (default 0).

socket type

describe

socket.AF_UNIX

Can only be used for interprocess communication on a single Unix system

socket.AF_INET

Network communication between servers

socket.AF_INET6

IPv6

socket.SOCK_STREAM

Streaming socket , for TCP

socket.SOCK_DGRAM

datagram socket , for UDP

socket.SOCK_RAW

Raw sockets, ordinary sockets cannot handle ICMP, IGMP and other network packets, but SOCK_RAW can; secondly, SOCK_RAW can also handle special IPv4 packets; in addition, using raw sockets, IP_HDRINCL sockets can be used Option to construct the IP header by the user.

socket.SOCK_SEQPACKET

Reliable continuous packet service

Create a TCP Socket:

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

Create UDP Socket:

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

2, socket function

important point:

1) When TCP sends data, a TCP connection has been established, so there is no need to specify an address. UDP is connectionless, and each time you send it, you need to specify who it is sent to.

2) The server and client cannot directly send lists, tuples, and dictionaries. Need to stringify repr

 

socket function

describe

Server socket function

s.bind(address)

Bind the socket to the address, under AF_INET, the address is represented as a tuple (host, port).

s.listen(backlog)

Start listening for incoming TCP connections. The backlog specifies the maximum number of connections the operating system can suspend before rejecting the connection. The value should be at least 1, and 5 should be fine for most applications.

s.accept()

Accepts a TCP connection and returns (conn, address), where conn is a new socket object that can be used to receive and send data. address is the address of the connecting client.

Client socket function

s.connect(address)

Connect to the socket at address. The format of the general address is a tuple (hostname, port). If there is an error in the connection, the socket.error error will be returned.

s.connect_ex(adddress)

The function is the same as connect(address), but returns 0 on success and the value of errno on failure.

public socket function

s.recv(bufsize[,flag])

Accepts data from a TCP socket. The data is returned as a string, and bufsize specifies the maximum amount of data to receive. flag provides additional information about the message and can usually be ignored.

s.send(string[,flag])

Send TCP data. Send the data in string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string.

s.sendall(string[,flag])

Send TCP data in full. Sends the data in string to the connected socket, but tries to send all the data before returning. Returns None on success, throws an exception on failure.

s.recvfrom(bufsize[.flag])

Accepts data from a UDP socket. Similar to recv(), but the return value is (data, address). where data is a string containing the received data and address is the socket address from which the data was sent.

s.sendto(string[,flag],address)

Send UDP data. Send data to the socket, address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.

s.close()

Close the socket.

s.getpeername()

Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr, port).

s.getsockname()

返回套接字自己的地址。通常是一个元组(ipaddr,port)

s.setsockopt(level,optname,value)

设置给定套接字选项的值。

s.getsockopt(level,optname[.buflen])

返回套接字选项的值。

s.settimeout(timeout)

设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如connect())

s.gettimeout()

返回当前超时期的值,单位是秒,如果没有设置超时期,则返回None。

s.fileno()

返回套接字的文件描述符。

s.setblocking(flag)

如果flag为0,则将套接字设为非阻塞模式,否则将套接字设为阻塞模式(默认值)。非阻塞模式下,如果调用recv()没有发现任何数据,或send()调用无法立即发送数据,那么将引起socket.error异常。

s.makefile()

创建一个与该套接字相关连的文件

3、socket编程思路

TCP服务端:

1 创建套接字,绑定套接字到本地IP与端口

  # socket.socket(socket.AF_INET,socket.SOCK_STREAM), s.bind()

2 开始监听连接    # s.listen()

3 进入循环,不断接收客户端的连接请求    # s.accept()

4 然后接收传来的数据,并发送给对方数据    # s.recv() , s.sendall()

5 传输完毕后,关闭套接字      # s.close()

TCP客户端:

1 创建套接字,连接远端地址

  # socket.socket(socket.AF_INET,socket.SOCK_STREAM), s.connect()

2 连接后发送数据和接收数据    # s.sendall(),  s.recv()

3 传输完毕后,关闭套接字    # s.close()

4、Socket编程之服务端代码:

import socket       # socket模块

sk = socket.socket()    # 定义socket类型,网络通信,TCP
sk.bind(('127.0.0.1',9000))     # 套接字绑定的IP与端口
sk.listen(1)     # 开始监听链接,监听1个请求

conn, addr = sk.accept()    # 接收客户端连接,并返回新的套接字与IP地址
ret = conn.recv(1024).decode('utf-8')   # 把接收的数据实例化
print(ret)      # 打印出对端发送过来的消息
conn.send('你好'.encode('utf-8'))     # 向客户端发送消息
conn.close()    # 关闭客户端套接字

sk.close()      # 关闭服务器套接字

5、Socket编程之客户端代码:

import socket

sk = socket.socket()    # 创建客户端套接字
sk.connect(('127.0.0.1', 9000))     # 尝试连接服务器
sk.send('你好吗'.encode())     # 发送消息给服务器
print(sk.recv(1024).decode('utf-8'))    # 打印服务端消息
sk.close()      # 关闭客户端套接字

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325275891&siteId=291194637