This article mainly introduces the Python+socket implementation of the TCP protocol based on the customer and server Chinese auto-reply chat function, combined with the case of the Python+socket implementation of the TCP chat program with automatic response function related operation methods and considerations, the need for friends can refer to the next
This paper describes the Python+socket implementation of the TCP protocol based on the client and server Chinese auto-reply chat function. Share to everyone for your reference, as follows:
"Spit Groove"
Online code to kill people, look at all write certainty, can run is a problem.
Some hobby code, like to collect code friends, see someone else's code paste copied over. But at least you have to try and run, look, Big Brother.
Body
Yesterday modified the C/S chat program running the UDP protocol, but the TCP protocol is not. Various tests, various pits.
After doing the following several modifications, finally can be:
1. Encode and decode the information sent and received separately
2, the 10th line of the client bind to connect( This is really a big hole!!) )
(This article is based on Windows 7 + Python 3.4)
The complete code is as follows (head guarantee, my pro-test normal!) ):
Server-side:
# tcp_server.py ' server ' from socket import *from time import ctimehost = ' #主机地址PORT = 23345 #端口号BUFSIZ = 2048 #缓存区大小, Unit is Byte, this sets the 2K buffer ADDR = (HOST, PORT) #链接地址tcpSerSock = socket (af_inet, SOCK_STREAM) #创建一个TCP套接字tcpSerSock. bind (ADDR) # Bind address Tcpsersock.listen (5) #最大连接数为5while True: #无限循环 print (' Try to connect client ... ') tcpclisock, addr = tcpsersock.accept () #等待接受连接 print (' link succeeded, client address is: ', addr) while True: data = TCPCLISOCK.RECV (Bufsiz) #接收数据, Bufsiz is the buffer size if not data:break #如果data为空, then jump out of the loop print (Data.decode ()) msg = ' {} The server has received [auto Reply] '. Format (CTime ()) Tcpclisock.send (Msg.encode ()) tcpclisock.close () #关闭连接tcpSerSock. Close () #关闭服务器
Client:
# tcp_client.py ' client ' from socket import *from time import ctimehost = ' localhost ' #主机地址PORT = 23345 #端口号BUFSIZ = 2048 # The buffer size, in bytes, is set at 2K buffers addr = (HOST, PORT) #链接地址tcpCliSock = socket (af_inet, sock_stream) #创建一个TCP套接字 #tcpclisock.bind ( ADDR) #绑定地址tcpCliSock. Connect (ADDR) #绑定地址while True: msg = input (' Please enter: ') #输入数据 if not msg:break #如果 msg is empty, then jump out of the loop C2/>tcpclisock.send (Msg.encode ()) data = Tcpclisock.recv (Bufsiz) #接收数据, Bufsiz is the buffer size if not data:break # If data is empty, jump out of loop print (Data.decode ())
Run
Experimental method: Run the server side first and then run the client
Then you can freely chat with the server on the client side: