Python Network programming-socket

Source: Internet
Author: User

Python provides two socket modules

Socket, which provides the standard BSD Sockets API

Socketserver, which provides server-centric classes to simplify the development of Web servers

Let's start with the socket module.

1. Socket type

Socket format:

Socket (Family,type[,protocal]) creates a socket with the given address, socket type, protocol number (default = 0)

Common types of sockets:

Socket. Sock_stream connection-oriented, TCP

Socket. Sock_dgram no connection, UDP

Create a TCP Socket:s=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

Create a UDP Socket:s=socket.socket (socket.af_inet,socket. Dgram)

2. Socket function

Note the point:

1) When the TCP data is returned, the TCP connection is established, so no address is required. UDP is for non-connected, each time it is sent to specify who to send.

2) python2.x version of the data is sent in string format, python3.x is the byte format, you need to be aware.

S.bind (address) binds a socket to an address and, under Af_inet, represents it in the form of a tuple (host,port)

S.listen starts listening for TCP incoming connections. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5.

S.accept () receives 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 location of the connection client.

S.connect (address) is connected to the socket at address. The format of the general address is a tuple (hostname,port), which returns a socket error if there is an error in the connection.

The S.CONNECT_EX function is the same as connect (address), but successfully returns 0, which fails to return the value of error.

S.RECV (Bufsize[,flag]) receives the data for the TCP socket. The data is returned as bytes bytes, bufsize Specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.

S.send (String[,flag]) sends TCP data. Sends data from a string to a 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]) sends the TCP data intact. Sends data from a string to a connected socket. However, it will attempt to send all data before returning. Successful return none, Failure throws an exception.

S.close () closes the socket.

3, Socket programming ideas

TCP Service side:

1 creating sockets, binding sockets to local IP and ports

S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

S.bind ()

2 Start listening for connections

S.listen ()

3 Enter the loop and continue to accept client connection requests

S.accept ()

4 then receive the incoming data, and send the data to the other side

S.RECV ()

S.sendall ()

5 When the transfer is complete, close the socket

S.close ()

TCP Client:

1 creating sockets, connecting remote addresses

S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

S.connect ()

2 Send data and receive data after connection

S.sendall ()

S.RECV ()

3 When the transfer is complete, close the socket

S.close ()

4, simple socket programming code? Server side:
123456789101112131415161718192021222324252627282930 #!/usr/bin/env python# -*- coding: utf-8 -*- import socket                #导入socket模块 ip_port=(‘127.0.0.1‘,9999)   #定义主机,端口号 s=socket.socket()            #实例化socket对象(买手机) s.bind(ip_port)              #绑定IP端口(买手机卡) s.listen(5)                  #建立5个连接池,等待接收请求,挂起连接  #等待电话conn,addr=s.accept()         #conn就是建立通信,负责收发消息的通道,每次只处理一个请求,                             #accept是阻塞请求,当第二个请求来的时候会进入listen连接池                             #挂起等待处理while True:    try:        recv_data = conn.recv(1024)             #收消息        if len(recv_data) == 0:break#如果客户输入为空的话退出        if recv_data == ‘exit‘:break #客户端退出,服务端跟着退出        send_data = recv_data.upper()                    print(send_data)        conn.send(send_data)                    #回复消息    except Exception:        break conn.close()                                    #挂电话,关闭连接通道
Client side:
123456789101112131415161718192021222324 #!/usr/bin/env python# -*- coding: utf-8 -*- import socket ip_port=(‘127.0.0.1‘,9999) s=socket.socket()  s.connect(ip_port)    #这里的connect实际是服务端的conn,与服务端建立连接  while True:    send_data=input(">>>: ").strip() #发送消息    if send_data == ‘exit‘:break    if len(send_data) == 0:continue    s.send(bytes(send_data,encoding=‘utf-8‘))     #收消息    recv_data=s.recv(1024)    print(str(recv_data,encoding=‘utf-8‘)) #挂电话s.close()



From for notes (Wiz)



Python Network programming-socket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.