Socket programming under python

Although the language has become python, the basic framework of socket is still there. First, let's take a look at the TCP framework in the UNIX environment




Then directly look at the program, open your IDLE, let's look at the server side first:

import socket # import socket library
import time # import time library
HOST = 'localhost' # connect to local server
PORT = 8001 # set the port number
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Select IPv4 address and TCP protocol
sock.bind((HOST, PORT)) # bind port
sock.listen(5) # Listen on this port, connect up to 5 devices
while True:  
    connection, address = sock.accept() # Accept the client's connection request
    try:  
        connection.settimeout(10) # Set the 10s time limit
        buf = connection.recv(1024) # Receive data instantiation
        if buf: # receive successfully
            print('connection success!')
            connection.send(b'welcome to server!') # Send message, b is bytes type
        else: # receive failed
            connection.send(b'please go out!')  
    except socket.timeout: # timeout
        print ('time out')
connection.close() # close the connection


Looking at the client side, it is simpler than the server side:

import socket
import time

HOST = 'localhost'
PORT = 8001
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)  
sock.connect((HOST, PORT))  
time.sleep(2)  
sock.send(b'1') # send message
print (sock.recv(1024).decode()) # Print the received message and decode it
sock.close() #Close the connection


Then we run the server side first, leaving it in a state of waiting to receive

Then run the client side, let's look at the running results of the two IDLE windows respectively




Since we can write complex TCP, UDP is even more of a problem.

We just need to modify the original code:

server side:

import socket  


HOST = 'localhost'
PORT = 8001
sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST, PORT))  
while True:
    buf, address = sock.recvfrom(1024)  
    if buf:
        print('connection success!')
        sock.sendto(b'welcome to server!',address)  
    else:  
        sock.sendto(b'please go out!',address)  
sock.close()   

client side:

import socket
import time

HOST = 'localhost'
PORT = 8001
sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)  
sock.connect((HOST, PORT))  
time.sleep(2)  
sock.send(b'1')
print (sock.recv(1024).decode())
sock.close()  

Please see my previous blog for the socket programming version of c language .




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325617228&siteId=291194637