First, in a simple hello / hi network chat program as an example, it uses the Socket API interface functionality is provided by the program python: The client sends a message to the server, the server returns a message to the client
server.py
Import Socket Host = ' 127.0.0.1 ' Port = 1234 serv_sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) serv_sock.bind ((Host, Port)) serv_sock.listen ( 10 ) # receiving client socket clnt_sock , addr = serv_sock.accept () MSG = clnt_sock.recv (1024 ) str_msg = msg.decode ( " UTF-. 8 " ) # returned to the client message r_msg = " the Hi, " + str_msg [10 :] clnt_sock.send ( r_msg.encode ( " UTF-. 8 ")) # Close the connection serv_sock.close () clnt_sock.close ()
client.py
Import Socket Host = ' 127.0.0.1 ' Port = 1234 our sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) sock.connect ((Host, Port)) # send data to the server MSG = INPUT ( " INPUT: " ) sock.send (msg.encode ( " UTF-. 8 " )) # receiving server returns the message to recive = sock.recv (1024 ) Print (to recive)
sock.close ()
In the simple chat program, a function call to the python provides the following network
socket.
socket
(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)socket.
connect
(Address), wherein the address is a tuple (socket.
bind
(address)socket.
listen
([backlog])socket.
accept
()