Opening of sockets

Socket:
Socket is an intermediate software abstraction layer for communication between the application layer and the TCPIP protocol family. It is a set of interfaces. In the design mode, Socket is actually a facade mode. It hides the complex TCP / IP protocol family behind the Socket interface. For users, a simple set of interfaces is all. Let Socket organize the data to meet the specified protocol.
It is also said that socket is a combination of IP + port, through the combination of the two to complete the positioning of the world's only host application.

Sockets originated in the 1970s at the University of California, Berkeley version of Unix, or BSD Unix. Therefore, sometimes people also refer to sockets as "Berkeley sockets" or "BSD sockets". In the beginning, sockets were designed to communicate between multiple applications on the same host. This is also known as inter-process communication, or IPC. There are two kinds of sockets (or called two races), which are file-based and network-based.

A file-based family in a
socket : AF_UNIX: Two socket processes run on the same machine, and a
network-based family in a communication socket can be indirectly completed by accessing the same file system :
AF_INET: a machine running on two machines Process, communicating according to internet protocol

Socket workflow:
We have two goals based on the transmission of the TCP protocol. The client and the server
let us first look at the client. First, we assume that we have obtained the data, so we first call the socket socket object. After we get the object, we Need to call the transport layer, first establish a TCP connection connect () interface, after calling the interface we get an object, send data and receive data by calling the method under the object.
Finally, close the link.
At the same time, let's look at the server. First, we must call the socket interface according to the protocol, and then use bind to bind a port number, so that we have a fixed and unique position. Next, define the size of the semi-linked pool. Take the link request from the semi-link pool to complete the link. After calling the interface, we get an object and send and receive data by calling the method under the object.
Finally, close the link.

Why do we need to fix the server location instead of the client?
We can think about it. If the location of the website we visit changes every day, what is the user experience? From this we conclude that the location of the server must be fixed. What about the client? Our ip is automatically acquired and the client cannot be hard-coded at the same time considering the high concurrency.

tcp协议简单完成
服务端
import socket
import subprocess
sever = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

sever.bind(("127.0.0.1",8080))

sever.listen(5)
while True:
    conn,addr = sever.accept()
    while True:
        try:
            data = conn.recv(1024)
            if len(data) == 0:break
            print(data.decode("utf-8"))
            conn.send(
                data.upper()
            )
        except Exception as err:
            print(err)
            break
    conn.close()

  

TCP protocol is simple to complete 
Client 
import socket 

client = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 

client.connect (("127.0.0.1", 8080)) 

while True: 
    msg = input ("input command") 
    if len (msg) == 0: continue 
    if msg! = "q": 
        client.send (msg.encode ("utf-8")) 
        data = client.recv (1024) 
        print (data) 
    else: 
        break 
client.close ( )

  

udp协议简单完成
服务端
import socket

sever = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

sever.bind(("127.0.0.1",8080))

while True:

    data,addr = sever.recvfrom(1024)
    print(data.decode("utf-8"))
    sever.sendto(data.upper(),addr)

  

The udp protocol is simply completed. 
client 
import socket 

client = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) 

while True: 

    data = input ("input information") 
    client.sendto (data.encode ('utf-8'), ( "127.0.0.1", 8080)) 
    msg, addr = client.recvfrom (1024) 
    print (msg)

  

tcp完成远程传输指令
服务端
import socket
import subprocess
sever = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

sever.bind(("127.0.0.1",8082))

sever.listen(5)

while True:
    conn,addr = sever.accept()
    while True:
        try:
            data = conn.recv(1024)
            if len(data) == 0:break
            res = subprocess.Popen(data.decode("gbk"),
                                   shell = True,
                                   stdout=subprocess.PIPE,
                                   stderr = subprocess.PIPE)
            stdout = res.stdout.read()
            stderr = res.stderr.read()
            conn.send(stdout)
            conn.send(stderr)

        except Exception as err:
            print(err)
            break
    conn.close()

  

客户端
import socket

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

client.connect(("127.0.0.1",8082))

while True :
    cmd = input("输入命令")
    if not cmd :continue
    client.send(cmd.encode("gbk"))
    res = client.recv(1024)
    print(res.decode("gbk"))

client.close()

  

udp simple chat room implementation 
import socket 

ip_port = ('127.0.0.1', 8081) 
udp_server_sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) # buy mobile phone 
udp_server_sock.bind (ip_port) 

while True: 
    qq_msg, addr = udp_server_sock. recvfrom (1024) 
    print ('A message from [% s:% s]: \ 033 [1; 44m% s \ 033 [0m'% (addr [0], addr [1], qq_msg.decode ('utf -8 '))) 
    back_msg = input (' reply message: ') .strip () 

    udp_server_sock.sendto (back_msg.encode (' utf-8 '), addr)

  

Client 1 
import socket 
BUFSIZE = 1024 
udp_client_socket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) 

qq_name_dic = ( 
    'dog brother alex' :( '127.0.0.1', 8081), 
    'blind donkey' :( '127.0. 0.1 ', 8081), 
    ' One Tree ':(' 127.0.0.1 ', 8081), 
    ' Wu Dalang ':(' 127.0.0.1 ', 8081), 
} 


while True: 
    qq_name = input (' Please select the chat partner: ') .strip () 
    while True: 
        msg = input (' Please enter a message, press Enter to send: ') .strip () 
        if msg ==' quit ': break 
        if not msg or not qq_name or qq_name not in qq_name_dic: continue 
        udp_client_socket.sendto (msg.encode ('utf-8'), qq_name_dic [qq_name]) 

        back_msg,addr=udp_client_socket.recvfrom(BUFSIZE)
        print ('A message from [% s:% s]: \ 033 [1; 44m% s \ 033 [0m'% (addr [0], addr [1], back_msg.decode ('utf-8') )) 

udp_client_socket.close () 

Client 2 
__author__ = 'Linhaifeng' 
import socket 
BUFSIZE = 1024 
udp_client_socket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) 

qq_name_dic = ( 
    'dog brother alex' :( '127.0.0.1', 8081), 
    'Blind Donkey': ('127.0.0.1', 8081), 
    'One Tree' :( '127.0.0.1', 8081), 
    'Wu Dalang' :( '127.0.0.1', 8081), 
} 


while True: 
    qq_name = input ('Please select a chat partner:') .strip () 
    while True: 
        msg = input ('Please enter a message, press Enter to send:') .strip () 
        if msg == 'quit':break
        if not msg or not qq_name or qq_name not in qq_name_dic:continue
        udp_client_socket.sendto (msg.encode ('utf-8'), qq_name_dic [qq_name])
 
        back_msg,addr=udp_client_socket.recvfrom(BUFSIZE)
        print ('A message from [% s:% s]: \ 033 [1; 44m% s \ 033 [0m'% (addr [0], addr [1], back_msg.decode ('utf-8') )) 

udp_client_socket.close ()

  

Guess you like

Origin www.cnblogs.com/Jicc-J/p/12756175.html