Socket programming,

Source: Internet
Author: User

Socket programming,

This blog does not discuss the development history and classification of sockets. It mainly describes how to use socket to build a basic client/server architecture.

A complete computer system consists of hardware, operating system, and application software. With these three conditions, a single computer system can play a single game. If you want to access the Internet (access a yellow website and send a yellow microblog), you need to abide by the network protocol, that is, the standard of communication between computers, according to the division of labor, Internet protocols can be logically divided into layers, that is, the ios layer-7 protocol. For details, see another blog. Reference blog (network communication principle): http://www.cnblogs.com/linhaifeng/articles/5937962.html

Starting from the server, the server first initializes the Socket, then binds the port (bind), listens to the port (listen), calls the accept blocking, and waits for the client to connect. At this time, if a client initializes a Socket and connects to the server (connect), if the connection is successful, the connection between the client and the server is established. The client sends a data request. The server receives the request and processes the request. Then, the response data is sent to the client. The client reads the data and closes the connection. The interaction ends.

 

 

Server socket function

S. bind () binding (host, Port Number) to socket

S. listen () Start TCP listening

S. accept () passively accepts TCP customers' connections and waits for the connection to arrive.

Client socket Functions

S. connect () Actively initializes TCP server connections

Extended version of s. connect_ex () connect () function. An error code is returned when an error occurs, instead of throwing an exception.

Common socket Functions

S. recv () receives TCP Data

S. send () sends TCP data (when the amount of data to be sent is larger than the remaining space in the cache area of the client, the data is lost and will not be completely sent)

S. sendall () sends complete TCP data (essentially, send is called cyclically. When the amount of data to be sent is larger than the amount of space in the cache, sendall does not lose data, and send is called cyclically until sending is complete)

S. recvfrom () receives UDP data

S. sendto () sends UDP data

S. close () close socket

Based on the relevant procedures and functions, we will first implement a simple communication.

Server

Import socketserver = socket. socket () server. bind ('2017. 25.0.0 ', 8080) # bind an ip address to the port server. listen (3) # In python3, The listen parameter must be set to 3, and the number of waiting queues is 3 while True: # receive different ip addresses cyclically, print port information ('waiting for online... ') conn, addr = server. accept () # blocking print ('new conn: ', addr) while True: # receive the same ip address cyclically. Port information try: # Exception Handling, when the server fails to receive or send data, the client is prompted to disconnect data = conn. recv (1, 1024 ). decode ('utf-8') print ('recv: ', data) while True: # If the input is empty, re-enter msg = input (' >>> :'). strip () if len (msg) = 0: continue else: break conn. send (msg. encode ('utf-8') # Send Response t ConnectionResetError as reason: print ('client has lost... \ n') breakserver. close ()

Client

Import socketclient = socket. socket () client. connect ('2017. 25.0.0 ', 8080) # connect to the server ip address, while the port is True: # It is null, and re-enter msg = input (' >>> :'). strip () if len (msg) = 0: continue client. send (msg. encode ('utf-8') # send data = client. recv (1, 1024 ). decode ('utf-8') # receives the print ('recv: ', data) client. close ()

In this way, when the server runs first, the client can connect to achieve one-stop communication. When the first connection is not disconnected, the subsequent connection can only wait for the former to be disconnected, otherwise, the client cannot receive messages from the latter. Note that an exception occurs when the first connection is disconnected. In Windows, the ConnectionResetError error is reported. You can use try... retry t... to catch exceptions. In linux, when the client is disconnected, the server will receive null values infinitely. We can use if to judge. In addition to simple communication, we can use the one-get-one principle to implement the Client Command server and receive the returned command results.

Server

Import socket, osserver = socket. socket () server. bind ('localhost', 9999) server. listen (3) while True: print ('waiting for online... ') conn, addr = server. accept () print ('new conn: ', addr) while True: print ('Prepare to receive instruction... ') cmd = conn. recv (1, 1024 ). decode ('utf-8') if not cmd: # in linux, when the client is disconnected, the null value print is sent infinitely ('client is disconnected... \ n') break print ('COMMAND execution: ', cmd) data = OS. popen (cmd ). read () # receives the string, and the execution result is also the string data = data. encode ('utf-8') data_size = len (data) conn. send (str (data_size ). encode ('utf-8') # size of data to be sent if data_size = 0: # if the command does not exist, the returned data size is 0 and only the data size is sent, do not send content print ('command does not exist... ') continue conn. send (data. encode ('utf-8') # send data print ('execution completed... \ n') server. close ()

Client

Import socketclient = socket. socket () client. connect ('localhost', 9999) while True: cmd = input ('input command, q exit \ n >>:') if len (cmd) = 0: print ('COMMAND cannot be blank... ') continue if cmd = 'q': break # exit the client. send (cmd. encode ('utf-8') # send the command data_size = client. recv (1024) # size of received data data_size = int (data_size.decode ('utf-8') if data_size = 0: # if the received data capacity is 0, the command does not exist print ('COMMAND does not exist... ') continue print ('size of received data', data_size) received_size = 0 # size of received data received_data = B ''# size of received data while data_size> received_size: # receive data cyclically and calculate the size of the received data # The last received data is the remaining data to prevent the occurrence of sticking packets due to continuous reception. if data_size-received_size> 1024: # receive more than once size = 1024 else: size = data_size-received_size # How much data is collected for the last receive = client. recv (size) received_size + = len (data) received_data + = data else: print ('execution completed ', received_size) # size of received data print () # for aesthetics, print data separately (received_data.decode ('utf-8') # print data client. close ()

Note: In TCP, when two consecutive messages are received, the packets are stuck, that is, (1) the data sending interval is very short, the data is very small, and the data is merged, generate a sticky package (2) the client sends a piece of data, and the server receives only a small portion of the data. The server receives the data from the buffer zone the next time and generates a sticky package. Solve the Problem of sticking packets, that is, (1) using the time module, time. sleep (0.5) increases by about 0.5 of the sending interval (2) Insert a receipt between two sending (3) strictly limit the size of data received each time. Next, we will simulate the download of files from the client on the server.

Server

Import socket, OS, hashlibserver = socket. socket () server. bind ('2017. 0.0.1 ', 8080) server. listen (3) while True: print ('waiting for online... ') conn, addr = server. accept () print ('new conn: ', addr) while True: print ('Prepare to receive instruction... ') cmd = conn. recv (1, 1024 ). decode ('utf-8') # receive client command if not cmd: # in linux, client disconnection means unlimited sending of null value print ('client disconnected... \ n') break cmd, filename = cmd. split () # For example, sending a file, sending filename, get filename print (filename) if OS. path. isfile (filename): f = open (filename, 'rb') m = hashlib. md5 () file_size = OS. stat (filename ). st_size # Get the file size conn. send (str (file_size ). encode ('utf-8') # send the file size conn. recv (1024) # Wait for the client to confirm for line in f: m. update (line) conn. send (line) f. close () conn. send (m. hexdigest (). encode ('utf-8') # Send md5 print ('sending completed... \ n') server. close ()

Client

Import socket, hashlibclient = socket. socket () client. connect ('2017. 0.0.1 ', 8080) while True: cmd = input ('>>> :'). strip () # execute download if len (cmd) = 0: continue if cmd. startswith ('get'): client. send (cmd. encode ('utf-8') data_size = int (client. recv (1, 1024 ). decode ('utf-8') print ('file size: ', data_size) client. send ('Prepare to receive... '. encode () # The client confirms to receive received_size = 0 filename = cmd. split () [1] f = open (filename + '. new', 'wb ') m = hashlib. md5 () while data_size> received_size: if data_size-received_size> 1024: # receive more than once, receive 1024 size = 1024 else: size = data_size-received_size # last receive, receive all data = client. recv (size) repeated ed_size + = len (data) m. update (data) f. write (data) else: f. close () new_md5 = m. hexdigest () # client md5 print ('Accept finished... ') old_md5 = client. recv (1, 1024 ). decode ('utf-8') # receive md5 print ('server file md5: ', old_md5) # verify md5 print ('client file md5:', new_md5) client. close ()

At this time, it is still a one-stop approach, which limits the efficiency of our communication and always feels too low.

Server

Import socketserver, timeclass MyTCPHandler (socketserver. baseRequestHandler): def handle (self): while True: try: self. data = self. request. recv (1, 1024 ). decode ('utf-8') print ('from: ', self. client_address) print ('[% s]: % s \ n' % (time. ctime (), self. data) self. request. send (self. data. upper (). encode ('utf-8') does t ConnectionResetError as reason: print ('{} has been deprecated... \ n '. format (self. client_address) breakif _ name _ = '_ main _': HOST, PORT = 'localhost', 9999 ADDR = (HOST, PORT) server = socketserver. threadingTCPServer (ADDR, MyTCPHandler) server. serve_forever ()

Client

import socketHOST, PORT = 'localhost', 9999ADDR = (HOST, PORT)client = socket.socket()client.connect(ADDR)while True:    msg = input('>>>:').strip()    if len(msg) == 0:continue    client.send(msg.encode('utf-8'))    data = client.recv(1024)    print('recv:',data.decode('utf-8'))client.close()

In this way, a single server can communicate with multiple clients. multithreading is used here. In addition, the principles and methods of multithreading, multi-process, and coroutine will be re-opened for separate narration.

The connection address will be used in the future.

After many practices, you have mastered simple communication, remote commands, file downloads, and one-to-many communication. You can develop a FPT program that supports multiple users online. The requirements are as follows:

1. User encryption authentication

2. Allow multiple users to log on simultaneously

3. Each user has his/her own home directory and can only access his/her home directory.

4. Disk Quota for users, with different available space for each user

5. allow users to switch directories on the ftp server at will

6. allow users to view files in the current directory

7. Allow upload and download of files to ensure file consistency

8. The progress bar is displayed during file transmission.

9. Additional Functions: supports resumable upload and download of Files

The connection address will be used in the future.

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.