Concurrent programming socket

import socket
from multiprocessing import Process
def serve(conn):
    ret = '你好'.encode('utf-8')
    conn.send(ret)
    msg = conn.recv(1024).decode('utf-8')
    print(msg)
    conn.close()

if __name__ == '__main__' :
    sk = socket.socket()
    sk.bind(('127.0.0.1',8080))
    sk.listen()
    try:
        while True:
            conn,addr = sk.accept()
            p = Process(target=serve,args=(conn,))
            p.start()
    finally:
        sk.close()

import socket

sk = socket.socket()
sk.connect(('127.0.0.1',8080))
msg = sk.recv(1024).decode('utf-8')
print(msg)
msg2 = input('>>>').encode('utf-8')
sk.send(msg2)
sk.close()
import socket
from multiprocessing import Pool

def func(conn):
    conn.send(b'hello')
    print(conn.recv(1024).decode('utf-8'))
    conn.close()

if __name__ == '__main__':
    p = Pool(5)
    sk = socket.socket()
    sk.bind(('127.0.0.1',8080))
    sk.listen()
    while True:
        conn, addr = sk.accept()
        p.apply_async(func,args=(conn,))
    sk.close()


import socket

sk = socket.socket()
sk.connect(('127.0.0.1',8080))

ret = sk.recv(1024).decode('utf-8')
print(ret)
msg = input('>>>').encode('utf-8')
sk.send(msg)
sk.close()
线程

import socket
from threading import Thread

def chat(conn):
    conn.send(b'hello')
    msg = conn.recv(1024).decode('utf-8')
    print(msg)
    conn.close()

sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
while True:
    conn,addr = sk.accept()
    Thread(target=chat,args = (conn,)).start()
sk.close()


import socket

sk = socket.socket()
sk.connect(('127.0.0.1',8080))

msg = sk.recv(1024)
print(msg)
inp = input('>>> ').encode('utf-8')
sk.send(inp)
sk.close()
协程

from gevent import monkey;monkey.patch_all()
import socket
import gevent
def talk(conn):
    conn.send(b'hello')
    print(conn.recv(1024).decode('utf-8'))
    conn.close()

sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
while True:
    conn,addr = sk.accept()
    gevent.spawn(talk,conn)
sk.close()

import socket
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
print(sk.recv(1024))
msg = input('>>>').encode('utf-8')
sk.send(msg)
sk.close()
Io nonblocking Model 

Import Socket 
SK = socket.socket () 
sk.bind (( ' 127.0.0.1 ' , 9000 )) 
sk.setblocking (False) 
sk.listen () 
conn_l = [] 
del_conn = []
 the while True:
     the try : 
        conn, addr = sk.accept ()   # do not block, but no one even I will complain 
        Print ( ' establish a connection: ' , addr) 
        conn_l.append (conn) 
    the except BlockingIOError:
         for CON in conn_l:
             the try:
                msg = con.recv(1024)  # 非阻塞,如果没有数据就报错
                if msg == b'':
                    del_conn.append(con)
                    continue
                print(msg)
                con.send(b'byebye')
            except BlockingIOError:pass
        for con in del_conn:
            con.close()
            conn_l.remove(con)
        del_conn.clear()
# while True : 10000   500  501


import time
import socket
import threading
def func():
    sk = socket.socket()
    sk.connect(('127.0.0.1',9000))
    sk.send(b'hello')
    time.sleep(1)
    print(sk.recv(1024))
    sk.close()

for i in range(2):
    threading.Thread(target=func).start()
io多路复用

import selectors
from socket import *

def accept(sk,mask):
    conn,addr=sk.accept()
    sel.register(conn,selectors.EVENT_READ,read)

def read(conn,mask):
    try:
        data=conn.recv(1024)
        if not data:
            print('closing',conn)
            sel.unregister(conn)
            conn.close()
            return
        conn.send(data.upper()+b'_SB')
    the except Exception:
         Print ( ' the closing ' , Conn) 
        sel.unregister (Conn) 
        conn.Close () 

SK = Socket () 
sk.setsockopt (SOL_SOCKET, the SO_REUSEADDR, . 1 ) 
sk.bind (( ' 127.0.0.1 ' , 8088 ) ) 
sk.listen ( 5 ) 
sk.setblocking (False) # set socket interface for non-blocking 
SEL = selectors.DefaultSelector ()    # to select a suitable mechanism for my IO multiplexed 
sel.register (sk, selectors.EVENT_READ , the Accept)
 # is equivalent to reading a list of select network in sk append an object, and a callback function to bind the Accept 
#It means if someone requests a connection sk, calls the method accrpt 

the while True: 
    Events = sel.select () # detect all sk, conn, if there is complete wait data stage 
    for sel_obj, mask in Events:   # [conn] 
        callback = sel_obj.data # the callback = Read 
        the callback (sel_obj.fileobj, mask) # Read (Conn,. 1) 


Import SELECT
 Import Socket 

SK = socket.socket () 
sk.bind (( ' 127.0.0.1 ' , 8000 )) 
sk.setblocking (False) 
sk.listen () 

read_lst = [SK]
 the while True:   # [sk,conn]
    r_lst,w_lst,x_lst = select.select(read_lst,[],[])
    for i in r_lst:
        if i is sk:
            conn,addr = i.accept()
            read_lst.append(conn)
        else:
            ret = i.recv(1024)
            if ret == b'':
                i.close()
                read_lst.remove(i)
                continue
            print(ret)
            i.send(b'goodbye!')


import time
import socket
import threading
def func():
    sk = socket.socket()
    sk.connect(('127.0.0.1',8000))
    sk.send(b'hello')
    time.sleep(3)
    print(sk.recv(1024))
    sk.close()

for i in range(20):
    threading.Thread(target=func).start()
# After synchronization submit a job to wait for the task is finished 
# asynchronous simply submit the task, do not wait for the task is finished you can do other things 
# blocking the Accept recvfrom recv 
# nonobstructive 

# blocked thread running state -> blocked -> ready 
# nonobstructive 

# IO multiplexing 
    # select mechanism Windows linux operating system is polling each item was listening to see if there is a read operation 
    # poll linux mechanism that can monitor objects can listen for more than a select mechanism 
                                 # with the increase in terms of listening, resulting in reduced efficiency 
    # epoll mechanism linux

Guess you like

Origin www.cnblogs.com/qwer-123/p/12052697.html