Python Full stack Development Foundation "18th" network programming (socket)

Source: Internet
Author: User

First, the network protocol

Client/server architecture

1. Hardware C/S Architecture (printer)

2. Software c/S architecture (the Internet is the C/s architecture): b/S architecture is a C/s architecture, B/S is a browser/server

The relationship between C/s architecture and socket: We use socket to complete the development of C/s architecture

OSI Layer Seven

Introduction:

Note A complete computer system is composed of hardware, operating system, application software three, with these three conditions, a computer systems can play with their own (play a single game, play a minesweeper what)

If you want to play with others, then you need to surf the internet, what is the Internet?

The core of the Internet is made up of a stack of protocols, which are standards, such as the standard of communication in the world is English.

If the computer is likened to human, the Internet Protocol is English in the computer world. All computers have learned the Internet Protocol, and all the computers can send and receive information according to the unified standard to complete the communication.

People divide the Internet protocol into logical hierarchy according to the Division of labor.

See network communication principle: http://www.cnblogs.com/linhaifeng/articles/5937962.html

Why do I have to learn the Internet protocol before learning socket?

First, the C/S architecture is based on network communication

Then the core of the network is a heap of network protocols, which is the protocol standard. If you want to develop a web-based communication software, you must follow these standards

Socke Layer

Second, what is the socket?

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

So, we do not need to understand the TCP/UDP protocol, the socket has been packaged for us, we only need to follow the socket rules to program, write the program is naturally follow the TCP/UDP standard.

Third, TCP-based socket

Classification of sockets:

Socket family based on file type: Af_unix (on UNIX systems, everything is file, file-based sockets call the underlying filesystem to fetch data, two socket processes run on the same machine at the same time, can communicate indirectly by accessing the same file system)

Socket family based on network type: af_inet (Python supports many address families, but since we only care about network programming, most of the time we only use af_inet)

Workflow for Sockets:

Let's give a little example of a phone call to illustrate

If you're going to call one of your friends, dial first, call when a friend hears a phone call, and you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. The scene in life explains how this works.

(If you go to a restaurant, assuming that the boss is the server, and you are the client, when you go to dinner, you definitely know that restaurant, which is the address of the server, but for yourself, the restaurant owner does not need to know your address.)

The simplest socket Function!!!

#1. Service End Socket Function Import Socket2 phone = Socket.socket (socket.af_inet,socket. SOCK_STREAM) 3 # 1. Server socket function 4 phone.bind (' Host IP address ', port number)  #绑定到 (host, port number) Socket 5 phone.listen () #开始TCP监听6 phone.accept () # Passively accept the TCP client connection, waiting for the connection to arrive in # #. Client socket Function 2 Import socket3 phone = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #买手机4 phone.connect ()  #主动连接服务端的ip和端口5 The extended version of the PHONE.CONNECT_EX ()  #connect () function, returning the wrong code when an error occurs, rather than throwing an exception
#3. Nested character phone.recv () #接受TCP数据phone for the public purpose of the server and client. Send () #发送TCP数据phone. Recvfrom () #接受UDP数据phone. SendTo () # Send UDP data Phone.getpeername () #接收到当前套接字远端的地址phone. GetSockName () #返回指定套接字的参数phone. setsockopt () #设置指定套接字的参数phone. Close () #关闭套接字
#面向锁的套接字方法phone. setblocking ()  #设置套接字的阻塞与非阻塞模式phone. settimeout ()  #设置阻塞套接字操作的超时时间phone. GetTimeout ()  #得到阻塞套接字操作的超时时间 # file-oriented socket function Phone.fileno ()  # Socket file Descriptor Phone.makefile () #创建一个与该套接字相关的文件

TCP is link-based, you must start the server before you start the client to link to the service side (three handshake to establish the connection before sending data)

Service side:

Import Socketphone = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #买手机phone. setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) #可以多次启动 # execution times will be error, then how to do? Just put it in front of the binding card. SetSockOpt method is ok phone.bind ((' 192.168.20.44 ', 8080)) #绑定手机卡 (IP, port) # port number is used by the system before 1024, 1024 After you write your own program to define the port print (' starting run ... ') Phone.listen (5) #开机   5 represents a maximum of 5 hangs, or a lot of while True: #链接循环    Coon,client_addr=phone.accept () #等待接电话, (Coon is the established link, the client's IP and the port number of the tuple)    print (coon,client_addr)    #收发消息    While True:  #通信循环        try:  #如果不加try ... except, it will error, because it does not know when you disconnect the link, the server thought you were running            data = COON.RECV (1024) # Received 1024 bytes of message            print (' Client data received message:%s '%data.decode (' Utf-8 '))            Coon.send (Data.upper ())  #发消息        Except Exception:  #因为你不知道客户端什么时候断开链接,            break    coon.close () #挂电话phone. Close () #关机 # Two ways to handle logic errors:    # If Judgment    # try...except Exception Handling # exception handling # When you know the condition of the direct error, you use the IF to judge the # when a program error must occur, but you can not predict what the condition of its error is, use Try...except

Client:

Import Socketphone = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #买手机phone. Connect ((' 192.168.20.44 ', 8080))  #直接连接服务端的ip和端口 # outgoing message while True:    msg = input (' > Strip ()  #用户输入    if not msg:continue  #如果为空就继续输    phone.send (Msg.encode (' Utf-8 '))  #  Send the message you entered    # phone.send (' Hello '. Encode (' Utf-8 '))    data = Phone.recv (1024x768)  #在接收一下    print (' Server back Res Service side return Result: >>%s '%data.decode (' Utf-8 ')) Phone.close ()

Attention:

If you are experiencing this problem when restarting the server:

This is because your service still exists four times the time_wait state of the wave in the occupied address (if not understand, please delve into the 1.tcp three times handshake, four waves wave 2.syn flood attack 3.) There will be a large number of optimization methods for time_wait state in case of high server concurrency. So how to solve it?

#加入一条socket配置, reuse IP and Port phone=socket (af_inet,sock_stream) phone.setsockopt (sol_socket,so_reuseaddr,1) #就是它, Add Phone.bind (' 127.0.0.1 ', 8080) before bind

  

Iv. impersonation of SSH remote execution commands based on TCP protocol  

 #服务端 
Import Socketimport subprocessphone=socket.socket (Socket.AF_INET, Socket. SOCK_STREAM) #买手机phone. Bind ((' 192.168.20.44 ', 8081)) #绑定手机卡phone. Listen (5) #阻塞的最大个数print (' starting ... ') while True: Conn,addr=phone.accept () #等待连接 print (addr,conn) while TRUE:CMD=CONN.RECV (10240) #接收的最大值 # if not cmd:b Reak print (' Received:%s '%cmd.decode (' Utf-8 ')) #处理过程 res=subprocess. Popen (Cmd.decode (' Utf-8 '), Shell=true, #Popen是执行命令的方法 stdout=subprocess. PIPE, Stderr=subprocess. PIPE) Stdout=res.stdout.read () Stuerr=res.stderr.read () conn.send (Stdout+stuerr) conn.close () Phon E.close ()
#客户端import Socketphone=socket.socket (Socket.af_inet,socket. Sock_stream) Phone.connect ((' 192.168.20.44 ', 8081)) #绑定端口while True:    cmd=input (' >> Please enter '). Strip ()    if Not  cmd:continue    phone.send (Cmd.encode (' Utf-8 '))    data=phone.recv (10240)    print (' return%s '% Data.decode (' GBK ')) Phone.close ()

  

Vi. socket based on UDP protocol

#服务端from Socket Import *udp_server = socket (Af_inet,sock_dgram) udp_server.bind ((' 127.0.0.1 ', 8080)) #绑定while true:# Communication Loop    msg,client_addr= udp_server.recvfrom    print (' Message Received:%s '%msg.decode (' Utf-8 '))    Udp_ Server.sendto (Msg.upper (), client_addr) Udp_server.close () # client # UDP No link, so send data money does not need to first establish a connection from socket import *udp_client = Socket (Af_inet,sock_dgram) while True:    msg = input (' >>: '). Strip ()    udp_client.sendto (Msg.encode (' Utf-8 '), (' 127.0.0.1 ', 8080))    res,sever_addr = Udp_client.recvfrom (1024x768)    print (' The result returned is:%s '%res.decode (' Utf-8 ')) Udp_client.close ()

Application of socket based on UDP protocol (simulated QQ chat)

# Server from socket import *udp_server= socket (Af_inet,sock_dgram) udp_server.setsockopt (sol_socket,so_reuseaddr,1) udp_ Server.bind (' 127.0.0.1 ', 8080) print (' Start running ... ') while true:qq_msg,addr = Udp_server.recvfrom (1024x768) print (' Come A message from [%s:%s]: \033[44m%s\033[0m '% (Addr[0],addr[1],qq_msg.decode (' Utf-8 '))) back_msg = input (' reply message:>> '). Strip () Udp_server.sendto (Back_msg.encode (' Utf-8 '), addr) udp_server.close () #客户端from socket Import *udp_client = Socket (af_inet,sock_dgram) Qq_name_dic = {' Room made ':(' 127.0.0.1 ', 8080), ' Chen Fengchen ':(' 127.0.0.1 ', 8080), ' Wang Yaling ':(' 127.0.0.1 ', 8080), ' radiant ':(' 127.0.0.1 ', 8080)}while true:qq_name = input (' Please enter the Chat object:>> '). Strip () if Qq_name not in Qq_name _dic:continue while true:msg = input (' Please input message, enter send: '). Strip () If msg== ' quit ': Break if not MSG or n        OT qq_name or Qq_name not in Qq_name_dic:continue udp_client.sendto (Msg.encode (' Utf-8 '), Qq_name_dic[qq_name])      BACK_MSG,ADDR = Udp_client.recvfrom (1024)  Print (' A message from [%s:%s]: \033[41m%s\033[0m '% (Addr[0],addr[1],back_msg.decode (' Utf-8 ')) Udp_client.close () 

Run results

V. subprocess Sub-process module

The import Subprocess#popen method is used to execute system commands and print the results directly to the terminal of the Res =subprocess. Popen (R ' dir ', shell=true,                       #r ' DSFSDFR ', Shell=true,                      # stdin= #标准输入 (not commonly used)                       stdout=subprocess. PIPE, #stdout standard output                       stderr=subprocess. PIPE) #stderr standard error # Gets the result of the ' GBK ' encoding, # This command may have the correct result, or there may be error results print (Res.stdout.read (). Decode (' GBK ') print (' ======== ') Print (Res.stdout.read (). Decode (' GBK '))  #说明只能读一次print (Res.stderr.read (). Decode (' GBK '))  #如果是错误的就会提示

Vi.. struct MODULE

#该模块可以把一个类型, such as numbers, to the fixed-length bytes type import struct# res = struct.pack (' i ', 12345) # Print (Res,len (res), type (res))  # The length is 4res2 = Struct.pack (' i ', 12345111) print (Res2,len (res2), type (res2))  #长度也是4unpack_res =struct.unpack (' I ', res2 ) print (Unpack_res)  # (12345111,) # Print (Unpack_res[0]) #12345111  

Python Full stack Development Foundation "18th" 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.