[Python3] simple socket programming demo

Divided into client and server

# Server program 
Import socket 
IF __name__ == ' __main__ ' : # 1. Create a socket (socket) objects Serv = socket.socket () # 2. Bind address information Host = socket.gethostname () Port = 12345 Serv .bind ((Host, Port)) # 3. open listening serv.listen (5) # maximum number sequences to wait, you can wait five, the sixth was rejected, usually the default is 5 Print ( " monitor is turned on , .... waiting for connection " ) # 4. wait for connection from the client the while . 1 : Conn, address = serv.accept () # Returns the socket connection object and the client address address, a tuple structure Print ( " connection address:% S " % (str (address [0]))) msg = " I am a service, please visit " conn.send (msg .encode ( ' UTF-. 8 ' )) serv.close ()

Which we encountered a error: a bytes-like object is required

The solution:
the solution is very simple, you only need to spend a function of bytes and encode python str two types of conversion (), decode () can be!

str by encode () method may be coded as specified in bytes;
conversely, if we read the byte stream from the network or disk, the data is read bytes. Bytes should become str, you require a decode () method;

 
 
# Client program

Import
Socket IF the __name__ == ' __main__ ' : Client = socket.socket () # 1. Create a connection to the server and the Host = socket.gethostname () Port = 12345 the client.connect ((Host, Port)) # receiving less than 1024 words section data MSG = client.recv (1024 ) client.close () Print (msg.decode ( ' UTF-. 8 ' ))

 

Then open the two terminals can be tested

Guess you like

Origin www.cnblogs.com/ronyjay/p/12560073.html