Python Network Programming

Source: Internet
Author: User

1, the server is a series of hardware or software, for one or more clients (service users) to provide the required "service." It exists for the sole purpose of waiting for requests from clients, responding to them (providing services), and then waiting for more requests.

2, the client/server architecture can be applied to both computer hardware and computer software.

3. Before the server responds to the client, it first creates a communication node that enables the server to listen for requests.

One, Socket: communication endpoint

1. Socket socket

Sockets are computer network data structures that embody the concept of "communication endpoints" as described in the previous section. Before any type of communication begins, the network application must create a socket.

There are two types of sockets: file-based and network-oriented.

2. Socket Address: host-Port pair

If a socket is like a phone jack-some infrastructure that allows communication, then the host name and port number are like the combination of area code and phone number. Valid port number range is 0-65535 (the port number less than 1024 is reserved for the system)

3. Connection-oriented sockets and sockets with no connections

Connection-oriented, a connection must be established before communication is made. The primary protocol that implements this type of connection is TCP (Transmission Control Protocol)

No connection, no connection is required before communication. The main protocol is UDP (User Datagram Protocol)

Second, the network programming in Python

1. Socket () module function

To create a TCP/IP socket: tcpsock = Socket.socket (socket.af_inef,socket. SOCK_STREAM)

Create UDP/IP socket: Udpsock = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)

2. Common socket object methods and properties

Name Describe
Server Socket method
S.bind () Bind an address (host name, port number pair) to a socket
S.listen () Set up and start the TCP listener
S.accept () Passively accept TCP client connections and wait until the connection arrives (blocked)
Client Socket method
S.connect () Proactively initiate TCP server connections
S.CONNECT_EX () The extended version of Connect, which returns the problem as an error code instead of throwing an exception
Common socket methods
S.RECV () Accept TCP Messages
S.send () Sending a TCP message
S.sendall () Complete sending of TCP messages
S.recvfrom () Receiving UDP messages
S.shutdown () Close connection
S.close () Close socket

3. Create a TCP server

SS = socket ()    #创建服务器套接字ss. bind ()            #套接字与地址绑定ss. Listen ()            #监听连接inf_loop:              #服务器无限循环    cs = ss.accept ()          #接收客户端连接    comm_loop:                #通信循环        cs.recv ()/cs.send ()    #对话 (Receive, send)    cs.close ()              # Close the client socket Ss.close ()               #关闭服务器套接字 (optional)
#!/usr/bin/env python#tcp Timestamp server from socket import *from time import ctimehost = ' PORT = 21567BUFSIZ = 1024ADDR = (host,po RT) Tcpsersock = socket (af_inet,sock_stream) tcpsersock.bind (ADDR) Tcpsersock.listen (5) while True:    print (' Waiting for connecting ... ')    tcpclisock, addr = tcpsersock.accept ()    print (' ... connected from: ', addr)    While True:        data = TCPCLISOCK.RECV (bufsiz)        if not data:            break        tcpclisock.send (' [%s]%s '% (bytes ( CTime (), ' Utf-8 '), data)    Tcpclisock.close () tcpsersock.close ()

4. Create a TCP Client

CS = socket () cs.connect () Comm_loop:    cs.send ()/cs.recv () Cs.close ()
#!/usr/bin/env python#tcp timestamp client from socket import *host = ' 127.0.0.1 ' PORT = 21567BUFSIZ = 1024ADDR = (host,port) tcpclisock = Socket (af_inet,sock_stream) Tcpclisock.connect (ADDR) while True:    data = input (' > ')    if not data:        break    tcpclisock.send (data)    data = Tcpclisock.recv (bufsiz)    if not data:        break    print (Data.decode (' Utf-8 '))    Tcpclisock.close ()

5. Create a UDP server

SS = socket () ss.bind () Inf_loop:    cs = Ss.recvfrom ()/ss.sendto () Ss.close ()
#!/usr/bin/env python#udp Timestamp server from socket import *from time import ctimehost = ' PORT = 21567BUFSIZ = 1024ADDR = (host,po RT) Udpsersock = socket (af_inet,sock_dgram) Udpsersock.bind (ADDR) while True:    print (' Waiting for message ... ')    Data, Addr=udpsersock.recvfrom (bufsiz)    udpsersock.sendto (' [%s]%s '% (CTime (), data), addr)    print (' ... Received from and returned to: ', addr)    udpsersock.close ()

6. Create a UDP client

CS = socket () Comm_loop:    cs.send ()/cs.recvfrom () Cs.close ()
#!/usr/bin/env python#udp timestamp client from socket import *host = ' localhost ' PORT = 21567BUFSIZ = 1024ADDR = (host,port) udpclisock = Socket (Af_inet,sock_dgram) while True:    data = input (' > ')    if not data:        break    Udpclisock.sendto ( DATA,ADDR)    data, Addr=udpclisock.recvfrom (bufsiz)    if not data:        break    print (data)    Udpclisock.close ()

  

Python Network Programming

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.