Iron python_day33_ Network Programming Socket Module 1

Source: Internet
Author: User

Iron python_day33_ Network Programming Socket Module 1
Part of the content is excerpted from the instructor's blog http://www.cnblogs.com/Eva-J/

Understanding sockets

A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces.
In design mode, the socket is actually a façade mode, which hides the complex TCP/IP protocol family behind the socket interface.
For the user, a simple set of interfaces is all, allowing the socket to organize the data to conform to the specified protocol.

In fact, standing on your point of view, the socket is a module.
We establish the connection and communication between two processes by invoking the methods already implemented in the module.
Some people say sockets as Ip+port,
Because IP is used to identify the location of a host in the Internet, port is used to identify an application on this machine.
So as long as we have the IP and port established, we can find an application and use the socket module to communicate with it.

The history of socket (socket)

Sockets originated in the the 1970s UC Berkeley version of Unix, which is what people call BSD Unix.
Therefore, sometimes people also refer to sockets as "Berkeley sockets" or "BSD sockets".
Initially, sockets are designed to be used for communication between multiple applications on the same host.
This is also called interprocess communication, or IPC.
There are two types of sockets (or two races), which are file-based and network-based.

Socket family based on file type

Socket family name: Af_unix
Unix all files, file-based sockets are called the underlying file system to fetch data,
Two socket processes run on the same machine and can communicate indirectly by accessing the same file system.

Socket family based on network type

Socket family name: af_inet
There are also af_inet6 used for IPv6, and some other address families,
However, they are either used only on a platform, or have been discarded, or are rarely used, or are not implemented at all,
Of all address families, Af_inet is the most widely used one, and Python supports a wide range of address families,
But since we only care about network programming, most of the time I only use af_inet.

The socket selection uses TCP or UDP protocol TCP (transmission Control Protocol) for a reliable, connection-oriented protocol (eg: call),

Low transmission efficiency full duplex communication (send cache & receive cache), byte stream oriented.
Applications that use TCP: Web browsers, e-mail, file transfer programs.

UDP (User Datagram Protocol) unreliable, non-connected service with high transmission efficiency (are chosen adequately before sending),

A pair of one or one-to-many, many-to-one, many-to-many, message-oriented, to do their best to serve, no congestion control.
Applications that use UDP: Domain Name System (DNS), video streaming, voice over IP (VoIP).

Socket (socket) Initial use of socket based on TCP protocol

Remember: TCP is connection-based, you must start the server and then start the client to connect to the server.

Example: TCP protocol Chat (one-to-one)-Server-side codeImportSocket fromSocketImportSol_socket, SO_REUSEADDR" "instantiate an object in the socket class in a socket module, for the sake of distinction, on the server I name serverscan be likened to buying a cell phone" "Server=Socket.socket ()" "before bind, this socket configuration is useful for reusing IP and ports.prevents the last exception from exiting before starting the report address in the use or port is occupied such errorscan be likened to real-name authentication, the following mobile phone number belongs to you." "Server.setsockopt (Sol_socket, SO_REUSEADDR,1)" "represents the IP address and port of the server bundle, where the loopback address 127.0.0.1 is filled in for native testing,Port is a number in the range of available ports of type int,can be likened to buying a mobile card." "Server.bind ((' 127.0.0.1 ',9527))# indicates that listening is turned onServer.listen ()# can be likened to the phone boot, can receive the signal# Agree to receive the client link and assign the client's link information to two variablesConn, addr=Server.accept ()# Curious words can print to see what the difference isPrint(conn)" "get the client information that is similar to the link that came in:<socket.socket fd=300, Family=addressfamily.af_inet,Type=socketkind.sock_stream, proto=0, laddr= (' 127.0.0.1 ', 9527),raddr= (' 127.0.0.1 ', 61463) >" "Print(addr)# Got a tuple that contains client IP and port (' 127.0.0.1 ', 61463)# make loop mode to keep interactive conversationsPrint(' This is the service side ') while 1:# Receive Bytes sent over by the clientRet=CONN.RECV (1024x768)# If the client sends q/q over, it means quitting chat    ifRet.upper== ' Q ': Break    # Print and decode to show it    Print(Ret.decode (' Utf-8 '))# service side also made can input feedback start embarrassed chat, a person a sentenceRes= input(' >>> '). Strip ()# Send method on behalf of sending message past client, need to transcodeConn.send (Res.encode (' Utf-8 '))# You can send a stop signal on your own side    ifRes.upper ()== ' Q ': BreakConn.close () Server.close () TCP protocol Chat (one-to-one)-Client-side codeImportSocketclient=Socket.socket () IP= input(' input server IP: ') port= input(' input port: ')# Connect to server via IP and portClient.Connect(IP,int(port)))Print(' This is the client ') while 1: Res= input(' >>> '). Strip ()# Client sends message to serverClient.send (Res.encode (' Utf-8 '))ifRes.upper ()== ' Q ': Break    # The client receives a message from the service side.Ret=CLIENT.RECV (1024x768)ifRet.upper ()== ' Q ': Break    Print(Ret.decode (' Utf-8 ') Client.close () The UDP protocol-based SOCKETUDP is not connection-based and can be accepted directly after the service is started, without the need to establish a connection in advance. UDP protocol-Service-Side code:ImportSocket fromSocketImportSol_socket, SO_REUSEADDR# Instantiate the socket object, Type=socket. Sock_dgram indicates that the protocol is UDPUdp_server=Socket.socket (type=Socket. SOCK_DGRAM) udp_server.setsockopt (Sol_socket, SO_REUSEADDR,1) IP= input(' Please enter the server listening IP: '). Strip () port= input(' Please enter the server listening port: '). Strip () Udp_server.bind (IP,int(port)))Print(' This is the service side ')# UDP does not require a connect-first connection like TCP while 1:# Unlike TCP, the UDP Receive method is RecvfromMSG, addr=Udp_server.recvfrom (1024x768)ifMsg.upper== ' Q ': Break    Print(Addr, Msg.decode (' Utf-8 ')) Res= input(' >>> '). Strip ()# also different is TCP send is send,udp is SendToUdp_server.sendto (Res.encode (' Utf-8 '), addr)ifRes.upper ()== ' Q ': BreakUdp_server.close () UDP protocol, client-side code:ImportSocketip= input(' input server IP: ') port= input(' input port: ') addr=(IP,int(port)) Udp_client=Socket.socket (type=Socket. SOCK_DGRAM)Print(' This is the client ') while 1: Res= input(' >>> '). Strip () Udp_client.sendto (Res.encode (' Utf-8 '), addr)ifRes.upper ()== ' Q ': BreakBack_msg=Udp_client.recvfrom (1024x768)[0]ifBack_msg.upper ()== ' Q ': Break    Print(Back_msg.decode (' Utf-8 '), addr) Udp_client.close () Example: Time synchronization server (pseudo) UDP server side:#!/usr/bin/env python# _*_ Coding:utf-8 _*_# Time Synchronization Service UDP protocol completed# N-Machine# 00:00, for example, reads some data from the database in a computer room with a standard Time server# All the machines in the engine room every once in a while to request this server to get a standard timeImportTimeImportSocket fromSocketImportSol_socket, So_reuseaddrserver=Socket.socket (type=Socket. SOCK_DGRAM) server.setsockopt (Sol_socket, SO_REUSEADDR,1) Server.bind (' 127.0.0.1 ',9527)) while 1:# receive a message in a time formatMSG, addr=Server.recvfrom (1024x768)if  notMsg# The default time formatTime_fmt= '%y-%m-%d %x'    Else: time_fmt=Msg.decode (' Utf-8 ')# server sends standard time to clientServer.sendto (Time.strftime (TIME_FMT). Encode (' Utf-8 '), addr) server.close () UDP client side:ImportTimeImportSocketser=(' 127.0.0.1 ',9527) Client=Socket.socket (type=Socket. SOCK_DGRAM) Client.sendto ('%y/%m/%d%h:%m:%s '. Encode (' Utf-8 '), Ser) ret, addr=Client.recvfrom (1024x768)Print(Ret.decode (' Utf-8 ')) Client.close ()

End

Iron python_day33_ Network Programming Socket Module 1

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.