"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 client 's first line 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!) ):
1 #tcp_server.py2 " "Server" "3 4 fromSocketImport*5 fromTimeImportCTime6 7HOST ="' #Host Address8PORT = 23345#Port number9Bufsiz = 2048#buffer size, unit is byte, here set 2K buffersTenADDR = (HOST, PORT)#Link Address One ATcpsersock = socket (af_inet, SOCK_STREAM)#Create a TCP socket -Tcpsersock.bind (ADDR)#Binding Address -Tcpsersock.listen (5)#Maximum number of connections is 5 the - whileTrue:#Infinite Loops - Print('try to connect the client ... ') -Tcpclisock, addr = Tcpsersock.accept ()#waiting to accept the connection + Print('the link is successful and the client address is:', addr) - + whileTrue: Adata = TCPCLISOCK.RECV (Bufsiz)#receive data, Bufsiz is the buffer size at if notData Break #if data is empty, jump out of the loop - Print(Data.decode ()) - -msg ='{} The server has received [auto Reply]'. Format (CTime ()) - Tcpclisock.send (Msg.encode ()) - inTcpclisock.close ()#Close Connection - toTcpsersock.close ()#shutting down the server
1 #tcp_client.py2 " "Client" "3 4 fromSocketImport*5 fromTimeImportCTime6 7HOST ='localhost' #Host Address8PORT = 23345#Port number9Bufsiz = 2048#buffer size, unit is byte, here set 2K buffersTenADDR = (HOST, PORT)#Link Address One ATcpclisock = socket (af_inet, SOCK_STREAM)#Create a TCP socket - #Tcpclisock.bind (ADDR) #绑定地址 -Tcpclisock.connect (ADDR)#Binding Address the - whileTrue: -msg = input ('Please enter:')#input Data - if notMsg Break #if msg is empty, jump out of the loop + Tcpclisock.send (Msg.encode ()) - +data = TCPCLISOCK.RECV (Bufsiz)#receive data, Bufsiz is the buffer size A if notData Break #if data is empty, jump out of the loop at 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:
Python+soket implementation of the TCP protocol client/server Chinese (auto-reply) Chat program