"Python" "socket"

Source: Internet
Author: User

"Server.py"

"""
#练习1
Import socket
Import threading

Sock = Socket.socket ()
Sock.bind (' 127.0.0.1 ', 8889)
Sock.listen (5)


def tcplink (CONN,ADDR):
# Sock.sendall (' Hello Socket '. Encode (' Utf-8 '))
Conn.send (bytes (' Hello world ', encoding= ' utf-8 '))
Conn.close ()

While True:
conn, addr = Sock.accept ()
t = Threading. Thread (target=tcplink,args= (CONN,ADDR))
T.start ()




#练习2: Chatting with a robot

Import Socketserver

Class Myserver (Socketserver. Baserequesthandler):
def handle (self):
conn = Self.request
Conn.sendall (' Hello, I'm a robot '). Encode (' Utf-8 '))
While True:
Ret_bytes = CONN.RECV (1024)
Ret_str = Ret_bytes.decode (' Utf-8 ')
if ret_str = = ' Q ':
Break
Conn.sendall (ret_str + ' Hello i good everybody good '). Encode (' Utf-8 '))

if __name__ = = ' __main__ ':
Server = Socketserver. Threadingtcpserver ((' 127.0.0.1 ', 8888), Myserver)
Server.serve_forever ()



#练习3 Uploading Files
Import socket

SK = Socket.socket ()
Sk.bind (' 127.0.0.1 ', 8887)
Sk.listen ()

While True:
CONN,ADDR = Sk.accept ()
Conn.sendall (' Welcome to my home '. Encode (' Utf-8 '))

Size = CONN.RECV (1024)
Size_str = Size.decode (' Utf-8 ')
file_size = Int (SIZE_STR)

Conn.sendall (' Start transfer '. Encode (' Utf-8 '))

Has_size = 0
f = open (' Db_new. JPG ', ' WB ')
While True:
if file_size = = Has_size:
Break
Date = CONN.RECV (1024)
F.write (date)
Has_size + = len (date)

F.close ()


‘‘‘
Reference: https://www.cnblogs.com/aylin/p/5572104.html "Using Select to implement pseudo simultaneous processing of multiple socket client requests" and "using Select to implement pseudo simultaneous processing of multiple socket client read and write separation"
Here are two examples I'm not running, I just want to explain this IO multiplexing implementation theory: Socketserver's threadingtcpserver can handle requests simultaneously thanks to select and threading two things, Essentially is the server side for each client to create a thread, the current thread to handle the corresponding client request, so, can support simultaneous n client link (long connection)
IO multiplexing

I/O (input/output), which is the input/output port. Each device will have a dedicated I/O address to handle its own input and output information first what is I/o:
I/O is divided into disk IO and network IO, which is said to be network IO
IO multiplexing:
I/O multiplexing refers to the ability to monitor multiple descriptors (sockets) Once a descriptor is ready (usually read-ready or write-ready), informing the program to read and write accordingly.
Linux
The Select,poll,epoll in Linux is a mechanism for IO multiplexing.
Under Linux network I/O uses socket sockets to communicate, the normal I/O model can only listen to a socket, and I/O multiplexing can listen to multiple sockets at the same time.
I/O multiplexing avoids blocking on Io, which would otherwise be multi-process or multi-threaded to receive multiple connected messages into a single process or single-threaded to save multiple sockets in the state after polling processing.
Python
Python has a select module, which provides: Select, poll, Epoll three methods, call the system's Select,poll,epoll, respectively, to achieve IO multiplexing.
1
2
3
4
5
6
7
8
9
10
11
Windows Python:

Available: Select

Mac Python:

Available: Select

Linux Python:

Available: Select, poll, Epoll
Methods for the Select module operation:
1
2
3
4
5
6
7
8
9
10
11
Handle list 11, handle list 22, handle list = Select.select (handle sequence 1, handle sequence 2, handle sequence 3, time-out)

Parameters: accepts four parameters (the first three must be)
Return value: three lists

The Select method is used to monitor the file handle, and if the handle changes, gets the handle.
1. When the handle in the parameter 1 sequence is readable (ACCETP and read), gets the changed handle and adds it to the return value 1 sequence
2. When the parameter 2 sequence contains a handle, all the handles in the sequence are added to the return value 2 sequence
3. When the handle in the parameter 3 sequence has an error, add the handle of the error to the return value 3 sequence
4. When the time-out is not set, select will block until the handle of the listener changes
5, when the time-out = 1 o'clock, then if the listener does not have any changes in the handle, then select will block 1 seconds, and then return three empty list, if the listener handle changes, it is executed directly.
‘‘‘
# Exercise 4 Using Select to implement my pseudo simultaneous processing of multiple socket client requests
Import Select
Import socket

Sk1 = Socket.socket ()
Sk1.bind (' 127.0.0.1 ', 8005)
Sk1.listen ()

Inpu = [Sk1,]
While True:
R_list,w_list,e_list = Select.select (inpu,[],[],1)
For SK in R_list:
If SK = = Sk1:
CONN,ADDR = Sk.accept ()
Inpu.append (SK)
Else
Try
ret = SK.RECV (1024x768). Decode (' Utf-8 ')
Sk.sendall (ret + ' Hao '). Encode (' Utf-8 '))
Except Exception as ex:
Inpu.remove (SK)


#练习5 socketserver Module Fork mode not on Windows, Mac never tried
From Socketserver import TCPServer, Forkingmixin, Streamrequesthandler
Import time


Class Server (Forkingmixin, tcpserver): # Custom Server class
Pass


Class MyHandler (Streamrequesthandler):
def handle (self): # overloaded handle function
addr = Self.request.getpeername ()
Print
' Get connection from ', addr # Print Client Address
Time.sleep (5) # Sleeps for 5 seconds
Self.wfile.write (' This is a forkingmixin TCP Socket server ') # Send information


Host = ' '
Port = 1234
Server = Server ((host, Port), MyHandler)

Server.serve_forever () # starts listening and processing connections

"""

#更详细的, reference: http://blog.csdn.net/taiyang1987912/article/details/40376067




"Client.py"
"""
#练习1
Import socket

Sock = Socket.socket ()
Sock.connect (' 127.0.0.1 ', 8889)

#ret = Sock.recv (1024x768). Decode (' Utf-8 ')
ret = str (SOCK.RECV (1024x768), encoding= ' Utf-8 ')
Print (ret)

Sock.close ()



#练习2 and Robot Chat

Import socket

obj = Socket.socket ()
Obj.connect (' 127.0.0.1 ', 8888)

Ret_bytes = OBJ.RECV (1024)
Ret_str = Ret_bytes.decode (' Utf-8 ')
Print (RET_STR)

While True:
INP = input (' Hello, what's your problem? \ >>> ')
If InP = = ' Q ':
Obj.sendall (Inp.encode (' Utf-8 '))
Break
Else
Obj.sendall (Inp.encode (' Utf-8 '))
Ret_bytes = OBJ.RECV (1024)
Ret_str = Ret_bytes.decode (' Utf-8 ')
Print (RET_STR)

#练习3 Uploading Files

Import socket
Import OS

obj = Socket.socket ()
Obj.connect (' 127.0.0.1 ', 8887)

Ret_bytes = OBJ.RECV (1024)
Ret_str = Ret_bytes.decode (' Utf-8 ')
Print (RET_STR)

Size = Os.stat (' Yan. JPG '). st_size
Obj.sendall (str (size). Encode (' Utf-8 '))

OBJ.RECV (1024)

With open (' yan.jpg ', ' RB ') as F:
For line in F:
Obj.sendall (line)




# # Exercise 4 using Select to implement my pseudo simultaneous processing of multiple socket client requests
Import socket

obj = Socket.socket ()
Obj.connect (' 127.0.0.1 ', 8003)

While True:
INP = input (' Please (q\ exit):\n>>> ')
Obj.sendall (Inp.encode (' Utf-8 '))
If InP = = ' Q ':
Break
ret = OBJ.RECV (1024x768). Decode (' Utf-8 ')
Print (ret)


#练习5 socketserver Module Fork mode not on Windows, Mac never tried
Import socket

s = Socket.socket () # Generates a socket object
Server = Socket.gethostname ()
Port = 1234
S.connect ((server, port)) # Connect to Server
Print
S.RECV (1024) # Read data
S.close () # Close connection

"""





"Python" "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.