socket programming examples

1.socket Programming

   Software testing and jmeter in order to achieve concurrent clients, jmeter principle is to use the thread pool,

   The purpose of software development for the realization of concurrent server-side support multi-user concurrent work

2. multithread socket server based concurrency

Client: 

'' ' 
The client user as long as the single communication loop
' ''
Import Socket
Client socket.socket = ()
the client.connect (( '127.0.0.1 ", 8090))
the while True:
client.send (' 33'.encode ( ' . 8-UTF '))
Data = client.recv (1024)
Print (Data)

'' ' 
Server for multi-user communication connection and to achieve circular
' ''
Embodiment 1: Thread pool
Import Socket
from the ThreadPoolExecutor concurrent.futures Import

Server socket.socket = ()

server.bind (
( '127.0.0.1 ", 9000)
)

server.listen (. 5)


# 1. packaged as a function of the communication cycle to achieve a multi-user creates a user channel
DEF RUN (Conn):
the while True:
the try:
Data = conn.recv (1024)
IF len (Data) == 0:
BREAK
Print (data.decode ( 'UTF-. 8'))
conn.send ( '111'.encode (' UTF-. 8 '))

the except Exception AS E:
BREAK

conn.Close ()


IF the __name__ ==' __main__ ':
print('Server is run....')
pool = ThreadPoolExecutor(50)
while True:
conn, addr = server.accept()
print(addr)
pool.submit(run, conn)



Embodiment 2: the number of concurrent not provided directly recycled
def communicate (conn): # a user channel 
the while True:
the try:
Data = conn.recv (1024)
IF len (Data) == 0:
BREAK
conn.send (data.upper ())
the except Exception AS E:
Print (E)
BREAK
conn.Close ()


DEF Server ():
Server socket.socket = ()
server.bind (( '127.0.0.1', 8989))
server.listen (. 5)
the while True:
Conn, addr = Server. Accept ()
T = the Thread (target = Communicate, args = (Conn,)) because in python # () may be represented by mathematical formulas in parentheses, and can represent tuples
t.start () # server function performs Communicate function as a thread, start () will make the start a thread

if __name__ == '__main__':
s = Thread(target = server)
s.start()


Guess you like

Origin www.cnblogs.com/bigbox/p/12040209.html