Python + Socket provides an example of the TCP-based Chinese automatic reply chat function between the client and the server,
This example describes how to use Python + Socket to automatically reply to a chat between a client and the server based on the TCP protocol. We will share this with you for your reference. The details are as follows:
[Tucao]
The Code on the internet killed people and looked at all the words to make them sound good. Running is a problem.
Some friends who love code and like to add code to favorites, paste and copy the code they see. But you should try again.
[Body]
Yesterday, I modified the C/S chat program running the UDP protocol, but none of the TCP protocol works. Various trials and pitfalls.
After making the following changes, you can finally:
1. encode and decode the sent and received information respectively.
2. Change bind on the client to connect (this is a big pitfall !!)
(This article is based on windows 7 + python 3.4)
The complete code is as follows (head of guarantee, I personally test it normally !) :
Server:
# Tcp_server.py '''server''' from socket import * from time import ctimeHOST = ''# host address PORT = 23345 # PORT number BUFSIZ = 2048 # cache size, in bytes, the buffer ADDR = (HOST, PORT) # link address tcpSerSock = socket (AF_INET, SOCK_STREAM) # creates a TCP socket tcpSerSock. bind (ADDR) # bind the address tcpSerSock. listen (5) # The maximum number of connections is 5 while True: # infinite loop print ('try to connect to the client... ') TcpCliSock, addr = tcpSerSock. accept () # Wait for accepting the connection print ('Connection succeeded, client address: ', addr) while True: data = tcpCliSock. recv (BUFSIZ) # receives data. BUFSIZ indicates the cache size. if not data: break # if data is empty, print (data. decode () msg = '{} the server has received [automatic reply]'. format (ctime () tcpCliSock. send (msg. encode () tcpCliSock. close () # close the connection tcpSerSock. close () # close the server
Client:
# Tcp_client.py '''client ''' from socket import * from time import ctimeHOST = 'localhost' # host address PORT = 23345 # PORT number BUFSIZ = 2048 # cache area size, the Unit is byte. Here, 2 K buffer ADDR = (HOST, PORT) # link address tcpCliSock = socket (AF_INET, SOCK_STREAM) # create a TCP socket # tcpCliSock. bind (ADDR) # bind the IP address tcpCliSock. connect (ADDR) # bind the address while True: msg = input ('enter: ') # input data if not msg: break # if msg is empty, the loop tcpCliSock will pop out. send (msg. encode () data = tcpCliSock. recv (BUFSIZ) # receives data. BUFSIZ indicates the cache size. if not data: break # if data is empty, print (data. decode ())
[Run]
Tutorial method: first run the server and then run the client
Then you can freely chat with the server on the client: