What we're sharing today is Python's simple client and server, here's just a few simple functions and make a play.
Before we get started, let's use a graph to show the relationship between them.
650) this.width=650; "Src=" Https://s3.51cto.com/oss/201711/13/3a0faab6c9d3cd7781bce8ea6a004ada.png-wh_500x0-wm_3 -wmp_4-s_2680642478.png "title=" 938876-20160611152927293-1786781422.png "alt=" 3a0faab6c9d3cd7781bce8ea6a004ada.png-wh_ "/>
Let's follow this step by introducing:
Service side:
Import socket
Server=socket.socket () #此处是为了创建出来一个服务端, the first step
Server.bind (' localhost ', 9999) #将套接字绑定到地址, Loclhost is the meaning of the local address, if you want to see the local address, open the console (run-"cmd") can be found by ipconfig
Server.listen (5) #进行监听
count=0# setting the number of messages accepted
While True: # Why need to add a loop, hehe, a server can not only accept a client bar.
conn, addr = Server.accept () # conn The tagged bit of the connection, the address of the addr connection, or another way of saying: Accept the connection and return (conn,address), where Conn is the new socket object that can be used to receive and send data. Address is the location of the connection client
Print ("New conn", addr) #打印对方地址
#接下来再来一个while True to keep receiving messages from a client
While True:
DATA=CONN.RECV (1024x768) #开始接受新消息, 1024 means the size of the received message
If not data: #没有数据
Print ("Client Disconnected")
Break
Print ("Execute Command", Data.decode ()) #对发过来进行打印
Conn.send (Data.upper ())
Count + = 1
If Count > 10:break
Server.close () #对服务端进行关闭
#客户端
Import socket
Client=socket.socket ()
Client.connect ((' localhost ', 9999)) #进行连接
#不断发送消息
While True:
Cmd=input (">>:"). Strip () #此函数可以用来发送信息,
Client.send (Cmd.encode ("Utf-8")) #服务器与客户端之间的连接需要用到utf-8 encoding
CMD_RECEIVE=CLIENT.RECV (1024)
Print ("recv:", cmd_receive)
Client.close () #对客户端进行关闭
Python---Client and server-side base (make a simple client and server)