Application: Analog QQ chat Client reference code
#Coding=utf-8 fromSocketImport*#Create socketTcpclientsocket =socket (af_inet, sock_stream)#Linked serverSERADDR = ('192.168.1.102', 7788) Tcpclientsocket.connect (seraddr) whileTrue:#Prompt user for data entrySendData = Raw_input ("Send:") ifLen (SendData) >0:tcpclientsocket.send (senddata)Else: Break #receive data sent from each other, maximum 1024 bytes receivedRecvData = TCPCLIENTSOCKET.RECV (1024) Print 'recv:', RecvData#Close SocketTcpclientsocket.close ()
Server-side Reference code
#Coding=utf-8 fromSocketImport*#Create socketTcpsersocket =socket (af_inet, sock_stream)#binding Local InformationAddress = ("', 7788) Tcpsersocket.bind (address)#socket created with socket the default property is active, use listen to make it passive, so you can receive links from othersTcpsersocket.listen (5) whileTrue:#If there is a new client to link to the server, then a confidence socket is created specifically for this client server #Newsocket is used to service this client #Tcpsersocket can be saved to wait for links to other new clientsNewsocket, clientaddr =tcpsersocket.accept () whileTrue:#receive data sent from each other, maximum 1024 bytes receivedRecvData = NEWSOCKET.RECV (1024) #if the length of the received data is 0, it means that the client has closed the link ifLen (RecvData) >0:Print 'recv:', RecvDataElse: Break #send some data to the clientSendData = Raw_input ("Send:") newsocket.send (senddata)#closing the socket for this client service, as long as it is turned off, means that it can no longer serve the client, and if service is required, it can only reconnect againnewsocket.close ()#turning off the listener socket, as long as the socket is closed, means that the entire program can no longer receive any new client connectionsTcpsersocket.close ()
Python network Programming (vii)