This article brings you the content is about how Python to achieve client and server-side data transmission, there is a certain reference value, the need for friends can refer to, I hope to help you.
Client
Def sock_client_data (): while True: try: s = socket.socket (socket.af_inet, socket. SOCK_STREAM) s.connect ((' 192.168.20.1 ', 6666)) #服务器和客户端在不同的系统或不同的主机下时使用的ip和端口, first check the IP # of the system network card where the server is located S.connect ((' 127.0.0.1 ', 6666)) #服务器和客户端都在一个系统下时使用的ip和端口 except Socket.error as msg: print (msg) Print (Sys.exit (1)) data = input ("Input data:") #输入要传输的数据 s.send (Data.encode ()) #将要传输的数据编码发送, If it is character data it must be encoded to send s.close () if __name__ = = ' __main__ ': sock_client_data ()
Server-side
Def socket_service_data (): try: s = socket.socket (socket.af_inet, socket. SOCK_STREAM) s.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) s.bind ((' 127.0.0.1 ', 6666) # Communication with the test IP under the same host's IP # s.bind ((' 192.168.20.1 ', 6666)) #在不同主机或者同一主机的不同系统下使用实际ip S.listen (Ten) except Socket.error as msg: print (msg) sys.exit (1) print ("Wait for Connection .......") while True: sock, addr = S.accept (), buf = SOCK.RECV (1024x768) #接收数据 buf = Buf.decode () #解码 Print ("The data from" + STR (addr[0]) + "is" + str (BUF) ) print ("successfully") # return BUF # sock.close () if __name__ = = ' __main__ ': socket_service_ Data ()
Operation Result:
Client:
Server-side:
Description:
1, the server and the client with a physical host under the same system using 127.0.0.1, the port itself set, as long as not be occupied, the Linux system to see whether the port is occupied command sudo netstat-nap | grep 6666 If the port is not found, it proves that the port is not occupied. Set up two. py files, one is sender.py, store client program, one is recieve.py, store server-side program, first run the server-side program, until the connection is successful and then run the client program, enter the data to be transferred, the server terminal to see the transmitted data is the transmission success.
2, the server and the client in the same physical host under different systems, then use the actual server system IP address, the author of Windows as a client, Linux as a server, in the Linux terminal input ifconfig view IP, two programs using the same IP and port, Deploy two programs to their respective systems, run the server-side program first, then run the client program and send the data until the server-side data is successfully received.