have been busy with experiments recently, occasionally have the opportunity to practice a long time not touched the socket, the previous study is in. NET, but all of the socket principle is the same, attach their own code (online down, debugging themselves)
Server-side:
#-*-coding:cp936-*-# #tcp响应服务器, when a connection is established with the client, the server displays the client IP and port while the client information is received and ' I get it! ' To the client, waiting for the input of a new message to be passed to the client. ##@ socket,tracebackhost= ' Port=12345s=socket.socket (socket.af_inet,socket. SOCK_STREAM) s.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) S.bind ((Host,port)) S.listen (1) while 1:try:clientsock,clientaddr=s.accept () except Keyboardin Terrupt:raise Except:traceback.print_exc () Continue Try:print ("Connection from:", CLIENTSOCK.GETP Eername ()) while 1:DATA=CLIENTSOCK.RECV (4096). Decode () if not Len (data): Brea K Print (Clientsock.getpeername () [0]+ ': ' +str (data)] Clientsock.sendall (Data.encode ()) Clie Ntsock.sendall (("\ni get it!\n"). Encode ()) t=input (' Input the word: ') Clientsock.sendall (T.encode ()) Except (keyboardinterrupt,systemexit): Raise Except:traceback.print_exc () Try:clientsock. Close () except KeyboardinTerrupt:raise Except:traceback.print_exc ()
Client:
Import socket,sysport=12345host=input (' Enter server IP: ') data=input (' Enter the message to send: ') s=socket.socket (socket.af_inet,socket. SOCK_STREAM) Try: S.connect ((host,port)) except: print (' Connection Error! ') S.send (Data.encode ()) S.shutdown (1) print (' Send complete. ') while 1: buf=s.recv (4096). Decode () if not Len (BUF): break sys.stdout.write (BUF)
Now, let's talk about some of the minor problems encountered:
1, as with the other compilation environment requires two processes to execute the server and the client, that is, open two shell scripts
2, the problem of the encoding method. The socket is sent in byte encoding, and Python3 uses Unicode encoding, so you need to use decode and encode functions to convert
3, this example is just a basic example of the function of functions, the actual use of the function must be extended, the object-oriented part of the added.
Socket Learning in Python3