TCP communication based on Sokcet under Python--Introductory article

Source: Internet
Author: User

Environment

Python version: 2.7

Ide:pycharm

TCP/UDP protocol is the transport layer of the Protocol, most of the communication between applications are using TCP or UDP, so in network communication and its importance, want to learn more about the differences between them, can refer to http://www.cnblogs.com/vathe/p/6815928.html

1. Simulate background programs to achieve browser access

Server-side code

# coding=utf-8Import socketdef handle_request (client): BUF= Client.recv (1024x768) Client.send ("http/1.1 ok\r\n\r\n"# This sentence allows the browser to access the Client.send ("Hello, TCP Socket"# Send the content to be displayed def main (): Sock=Socket.socket (socket.af_inet, socket. Sock_stream) Sock.bind (('localhost',8090) # Set IP (or domain name) and port number Sock.listen (2) # Set maximum concurrent number while 1: Conn, address=sock.accept () # Receive request Handle_request (conn) # Processing Request Conn.close () # Close Connection if__name__ = ='__main__': Main ()

accessing localhost:8090 using a browser

2. Simulated Doraemon Program (client sends information, returns source data from server)

A. servertcp.py Code

# coding=utf-8Import socketdef handle_request (conn): Conn.send ("Server:hello, let ' s start") Flag=True whileFlag:data= Conn.recv (1024x768)        ifdata = ='Exit': Flag=FalseElse: Conn.sendall (data) def main (): Sock=Socket.socket (socket.af_inet, socket. Sock_stream) Sock.bind (('localhost',8091) # Set IP (or domain name) and port number Sock.listen (2) # Set maximum concurrent number while 1: Conn, address=sock.accept () # Receive request print address, handle_request (conn) # Processing Request Conn.close () # Close Connectionif__name__ = ='__main__': Main ()

b.clienttcp.py

# coding:utf-8Import Socketclient=Socket.socket (socket.af_inet, socket. SOCK_STREAM) Address= ('localhost',8091) Client.connect (address) while 1: Data= Client.recv (1024x768) # client.send ('Client:ok, let\ ' s begin') Print Data InP= Raw_input ('Client:') client.send (INP)ifINP = ='Exit': # Enter exit, Exit Break

C. Two program interaction results

A brief analysis of socket class in 3.socket module

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

Parameter one: Address type

Socket.af_inet, which represents the use of IPV4 type IP, the default type

Socket.af_inet6, indicating the use of IPV6 type IP

Socket.af_unix, which represents a socket that uses two-process communication from the same device in a UNIX system

Parameter two: Packet format

Socket. Sock_stream streaming socket, for TCP (default)

Socket. SOCK_DGRAM datagram socket, for UDP

Socket. Sock_raw the original socket, the ordinary socket can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, the use of the original socket, can be IP_ The HDRINCL socket option constructs an IP header by the user.

Socket. SOCK_RDM is a reliable form of UDP that guarantees the delivery of datagrams but does not guarantee the order. Sock_ram is used to provide low-level access to the original protocol, which is used when certain special operations are required, such as sending ICMP packets. Sock_ram is typically used only by advanced users or by programs that are run by administrators.

  Socket. Sock_seqpacket Reliable Continuous Packet service

Socket.bind (Address)

  Fixed address, including host and Port. The host can use IP or domain name identification.

Socket.listen (Backlog)

Setting the maximum number of concurrent

Socket.connect (address)/socket.connect_ex (address)

The client requests to establish the connection, address represents the addresses, the difference is, if the connection is an exception, the former directly reported an exception, the latter returned an error code, the program continues to run

Conn, address = Socket.accept ()

The server receives the request to establish a connection and returns the connection and address.

Socket.close ()

Close connection

SK.RECV (Bufsize[,flag])

Accepts the data for the socket. The data is returned as a string, and bufsize specifies the maximum quantity that can be received.

Sk.recvfrom (Bufsize[.flag])

Similar to recv (), but the return value is (data,address).

Sk.send (String[,flag])

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. That is, the specified content may not be sent all.

Sk.sendall (String[,flag])

Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.

Internally, the send is called recursively, sending all the content.

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

Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent. This function is mainly used for UDP protocol.

TCP communication based on Sokcet under Python--Introductory article

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.