A nonsense: Recently learned Python core programming, ran into a simple (how easy to see) TCP Server and client black screen flash back issues
Reason:
>>>from Socket Import *
>>> Help (SOCKET.RECV)
Help on Method_descriptor:
Recv (...)
Recv (buffersize[, Flags]), data
Receive up to buffersize bytes from the socket.
>>> Help (Socket.send)
Help on Method_descriptor:
Send (...)
Send (data[, flags]), count
Send a data string to the socket.
Because the working mode is: Client send-server receive-server send-client receive
That is, the data type sent by the client must conform to the type of data received by the server, the byte stream, expressed as
Client: Send, Data.encode (), because you want to receive the server
Server: Receive, Data.decode (), because you want to send the server
Server: Send, Data.encode (), because to be received by the client
Client: Receive, Data.decode, because the output is to be displayed
The detailed code is as follows:
Server:
From socket Import *
From time import CTime
Host= "
port=3306
bufsize=1024
Addr= (Host,port)
Sst=socket (Af_inet,sock_stream)
Sst.bind (ADDR)
Sst.listen (5)
While True:
Print (' .... Wait Connect .... ')
Cst,addr=sst.accept ()
Print (' .... Connect from ', Addr, ' .... ')
While True:
DATA=CST.RECV (BufSIZE). Decode ()
Cst.send (Data.encode ())
Cst.close ()
Sst.close ()
Client:
From socket Import *
host= ' localhost '
port=3306
buffsize=1024
Addr= (Host,port)
Cst=socket ()
Cst.connect (ADDR)
While True:
Data=input (' > '). Encode ()
Cst.send (data)
DATA=CST.RECV (buffsize). Decode ()
Print (';: ', data)
Please forgive me for your shortcomings.
The following questions are attached:
1.socket.send () request is a string parameter, Data.encode () Why not error, after the code is not a string specified?
The 2.TCP server is a dead loop, but when you close the client, it quits with an exception, how do I change it?
3. The client is also a dead loop, when the server shut down when he did not know, run without error, how to let the client know that the server shut down?
This article is from the "Python" blog, so be sure to keep this source http://52syc.blog.51cto.com/10591392/1775643
Python TCP Client Server fallback problem (beginner)