Python TCP Socket

Source: Internet
Author: User

Socket (socket), the endpoint of the Transport Layer communication, consisting of an IP and a port number (Ip,port), which can be used to accurately locate and communicate with the process on the server through the socket

python2.6 implementation, based on af_inet (network sockets)
Type Socket_stream (TCP socket), Socket_dgram (UDP socket)

TCP Socket Communication Logic
TCP Service side: Create socket>>> bind the ground server >>> listen for connection >>> communication interaction >>> Close Connection
TCP client: Create socket>>> to establish connection >>> communication interaction >>> Close Connection

Python TCP Socket Service side

1     #!/usr/bin/python2     #-*-coding:utf-8-*-3 4     #filename:Tdpsocket.py5     #Author:6     #Create date:2015-03-257     #Modify Date:8     #description:tcp Socket9 Ten     #Import Stander Lib One      fromSocketImportsocket, af_inet, Sock_stream A     ImportSYS -Sys.path.append ('..' ) -  the  -     classtcpsocket (): -         " " - Tcpsocket class, establishes the TCP socket server, obtains the configuration information to establish the connection + Usage: - p = tcpsocket.tcpsocket () + P.listen () A Infinite loop Listening port, process rewrite data processing method at         " " -          -         def __init__(self): -             " " - Initialize, establish SOCKET,IP port bindings -             " " inSelf.tcpserversocket = socket (af_inet, SOCK_STREAM)#Create a TCP socket -             #Port number is 0-65535,0-1023 for system reserved, dynamic port 49152-65535, service using port 1024-49151 interval toSelf.tcpServerSocket.bind (('127.0.0.1', 20015) ) +Self.tcpServerSocket.listen (5) -Self.buffer_size = 1024#buffer is 1k the              *              $         defBulidconnect (self):Panax Notoginseng             " " - establish a connection, get information about the connection client, receive data the             " " +Tcpclientsocket, addr =self.tcpServerSocket.accept () A             Print 'Conn from:', addr theRaw_data =tcpclientsocket.recv (int (self.buffer_size)) +             Print 'Receive data:', Raw_data -              $             return(Tcpclientsocket, Raw_data) $              -  -         defprocess (self, data): the             " " - socket transfer data processing, inheritance override this functionWuyi             " " theresult =Data -             returnresult Wu  -          About         defSend (self, TCP, result): $             " " - return information, close connection -             " " -Tcpclientsocket =TCP A tcpclientsocket.send (Result) + tcpclientsocket.close () the              -          $         defListen (self): the             " " the listening port, infinite loop the             " " the              whileTrue: -                 Print 'Wati for Connect:' inSocket_data = Self.bulidconnect ()#Establish a connection theresult = Self.process (socket_data[1])#receive information, process information theSelf.send (socket_data[0], result)#returning information to the client About self.close () the          the          the         defClose (self): +             " " - Close Connection the             " "Bayi self.tcpServerSocket.close () the  the              -         def __del__(self): - self.close () the  the  the     if __name__=='__main__': thep =Tcpsocket () -P.listen ()

Python TCP Socket Client

1     ImportSocket2 3Sock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)4Server_address = ('127.0.0.1', 20015 )5 6     Print 'connecting to%s:%s.'%server_address7 Sock.connect (server_address)8 9Message ="I ' m TCP client"Ten     Print 'sending "%s".'%message One  ASock.send ('[{"url": "Www.baidu.com"}]' ) -     Print 'receive from server:', SOCK.RECV (1024) -  the sock.close () -     Print 'Closing socket.'

Python TCP Socket

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.