Python-network Programming-socket Programming

Source: Internet
Author: User

first, socket Syntax

Network Seven layer model (osi Model)

1 Physical layer-->2 Data link Layer (mac address)-->3 Network layer (ip)-->4 Transport Layer (tcp/wireless, UDP Protocol transport)-->5 session layer-->6 presentation layer-->7 application layer (http, ftp, smtp, Pop3)

socket syntax and related knowledge points:

The socket is a two-way channel for two programs to achieve data transfer. The network communication is the specific service that locates the specific target machine through ip+port, the operating system has 0-65535 ports, each port provides the service independently.

There must be two ports to build a socket: server and client

server : Passively waits for client requests to be accepted

Setup Process: 1. Create a Socket instance Sk-->sk.bind () set the network address and port number that the server can listen On-->sk.listen () start listening--

Cnn,val=sk.accepr () accepts the Client's connection-->cnn.recv () accepts Data-->cnn.send () sends Data-->close

1, establish a socket instance: socket.socket ()

1 Import Socket 2 server=socket.socket (socket.af_inet,socket. Sock_stream)

The first parameter is: address cluster

Socket.af_inet IPv4

Socket.af_inet6 IPV6

Socket.af_unix UNIX native-to-computer Communication

       

Second Parameter: socket type

Socket. Socket_stream for TCP

Socket. Socket_dgram for UDP

  Socket. sock_raw   Raw sockets, normal sockets cannot handle network messages such as icmp, igmp, and Sock_raw can; Sock_raw can also handle special IPv4 messages, and with the original sockets, the IP header can be constructed by the user through the IP_HDRINCL socket Option.

        socket.SOCK_RDM       是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。

2. Binding address: Sk.bind

The format of address is dependent on the addressing cluster, and if it is IPV4, the address is passed in as Ganso

1 server.bind (('0.0.0.0', 8001))

3, Start listening: Sk.listen (backlog)

Start listening for incoming connections, the backlog represents the maximum number of connections that can be suspended before a connection is denied, with a backlog of up to 5

1 server.listen (5)

4. Receive the connection and return the new socket object and client address

1 cnn,client_addr=server.accept ()

CNN for the new socket object, Clinet is the client address of the connection

5. Accept and send client data

1 cnn.recv (1024x768)2 cnn.send (b'got your msg')

Client : Proactively sending requests to the server

Process: establish a socket instance C-->c.connect () connection server-->c.send () send data-->c.recv () accept Data-->c.close ()

1 ImportSocket2Client=socket.socket ()#1. Set up socket instance3Client.connect (('localhost', 8001))#2. Connection4Msg=input ('>>:')5Client.send (msg.encode ())#3. Send data6 Print('send:%s'%Msg)7Data=client.recv (1024)8 Print('receive from server:%s'%data)#4. Acceptance of data

Here's a little Exercise:

Service Side:

1 ImportSocket2Server=Socket.socket (socket.af_inet,socket. Sock_stream)3Server.bind (('127.168.0.1', 8001))4Server.listen (5)5 Print('------------start to listen--------')6  whileTrue:#when the client disconnects from the server, it prevents the error from jumping out of the second loop, but returns to the loop and re-accepts the request from the other Client.7Cnn,client_addr=server.accept ()8     Print(cnn,client_addr)9      whileTrue:Ten         Try: oneData=cnn.recv (1024)#There is a client disconnect is, recv is not connected, will error, use try to do exception handling, to prevent program termination a             Print('client:%s'%Data) -S_data=input ('Service Side:') - cnn.send (s_data.encode ()) the         exceptConnectionreseterror as E: -             Print(e) -              break

Client:

1 ImportSocket2Client=Socket.socket ()3Client.connect (('127.168.0.1', 8001))4 5  whileTrue:6Msg=input ('client:')7 client.send (msg.encode ())8     #print (' send:%s '%msg)9Data=client.recv (1024)Ten     Print('Service side:%s'%data)

Python-network Programming-socket Programming

Related Article

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.