How does a socket in Python work?

Source: Internet
Author: User

This article and we share the main is the Python socket related content, together to see it, hope to learn Python to help you.one. Socket ModuleSocket, commonly known as socket, is actually a combination of IP address and port. Similar to this form (IP, port), where IP represents a host, port represents an application, we can communicate through a socket and another host. About the socket source code parsing in the Tarnado series article, is writing in .....1. Means of communicationTCP Communication UDP communication UNIX-based communication2. How to Socket# It's just so much to know for a while, and then I'll keep on saving methods ofSocketObjects (keyword arguments notAllowed): _accept ()--AcceptConnection, returning newSocketFd andClient AddressBind(addr)--BindTheSocketto aLocalAddress to bind a localSocketSocketsClose() --CloseTheSocketClose a socketConnect(addr)--ConnectTheSocketTo a remote address connected to the remote host CONNECT_EX (addr)--Connect,returnAn error code instead of an exceptiondup ()--returnA newSocketFD duplicated from Fileno () Fileno ()--returnUnderlying file descriptorGetpeername() --returnRemote Address
  • getsockname() --returnLocalAddressgetsockopt(Level, optname[, Buflen])--getSocketOptionsgettimeout ()--returnTimeoutorNoneListen([n])--Start listening forIncoming connectionsrecv(buflen[, Flags])--Receive data Recv_into (buffer[, nbytes[, flags])--receive data (into a buffer) , Recvfrom (buflen[, Flags])--Receive data andSender ' s Addressrecvfrom_into (buffer[, nbytes, [, flags])--Receive data and sender 'sAddress (into a buffer) Sendall (data[, Flags])--SendAll data sent to the remote host, after 3.x can only send byte form, so at the time of transmission is generally to be converted bytesSend(data[, Flags])--SendData, May notSendAll of it is also sending data, the difference isSendSent incomplete, randomly sent, two sendall sent the full sendto (data[, flags], addr)--SendData to agivenAddress setblocking (0 | 1)--set for sending data based on UDPorClear the blocking I/O flag is set to block mode 0 for blocking, 1 for non-blockingsetsockopt(Level, optname, value)--SetSocketOptions set someSocketEucalyptus settimeout (None | float)--setorClear the Timeout setting time-out marketshutdown(how)--shut down traffic in oneorBoth Directionsif_nameindex ()--returnAll network Interface Indices andNamesif_nametoindex (name)--returnThe corresponding interfaceIndexIf_indextoname (Index) --returnThe corresponding interface name
  • not available on all platforms!
  • two. Simple chat robotIf a data is sent, the server will reply to a data + Hello 1 #-*-coding:utf-8-*-2 # zhou3 # 2017/7/345ImportSOCKET6 # Create a server object 7 Server_obj = Socket.socket () 8 # Bind Port 9 Server_obj.bind (("127.0.0.1", 8888,)) 10 # Set the wait queue length for listening Degree of 5, when greater than 5 refused to connect one by one Server_obj.listen (5) 1213 whileTrue: 14 # Waits for the client to accept the connection, for blocking mode conn, address = server_obj.accept () 16 # Send Welcome message Conn.sendall (bytes ("Welcome to the simple Chat room: ", encoding= ' Utf-8 ')) 18 whileTrue: 19 # Receiving the message from the opposite side will add you to the back of the message. Re-send it back. ret = str (CONN.RECV (1024x768), encoding= ' Utf-8 ') 21ifret = = ' Q ': 22 # If the opposite is sent for Q then exit 23 BreakConn.sendall (bytes (ret + "Hello", encoding= ' Utf-8 ')) server#-*-coding:utf-8-*-# zhou# 2017/7/3importSocketClient =Socket.Socket() Client.connect (("127.0.0.1", 8888,)) # Accept the Welcome message and PRINT ret = str (CLIENT.RECV (1024),encoding= ' Utf-8 ') print (ret) whileTrue:message = input ("Please enter what you want to send:") Client.sendall (bytes (Message,encoding= ' utf-8 '))ifmessage = = ' Q ': Breakret = str (CLIENT.RECV (1024),encoding= ' Utf-8 ') print (ret) clientthree. Simple FTP uploadImplemented to upload a picture to server Side 1 #-*-Coding:utf-8-*-2 # zhou3 # 2017/7/245Importsocket67 Server = Socket.socket () 8 Server.bind (("127.0.0.1", 9998,)) # Bind IP9 Server.listen (5) 1011 whileTrue: conn, address = Server.accept () 13 # First receive file size after connection file_size = Int (str (CONN.RECV (1024x768), encoding= ' Utf-8 ') 15 # Conn.sendall (bytes ("1001", encoding= ' utf-8 ') to solve the sticky packet problem) 17 # The file size accepted is has_size = 019 num = 120 # Receive files after connection F = open ("New.jpg", ' WB ') 22 whileTrue: num + = 124ifFile_size = = has_size:25 Breakdata = CONN.RECV (1024x768) f.write (data) Has_size + = len (data) F.close () # Close File Ftpserv Er1 #-*-Coding:utf-8-*-2 # zhou3 # 2017/7/2456ImportOs7Importsocket89 client = Socket.socket () 1011 Client.connect (("127.0.0.1", 9998), 12 # transfer File Size file_size = Os.stat ("1.jpg"). St_ Size14 Print (file_size) 15 # Send File size of Client.sendall (bytes (str (file_size), encoding= ' Utf-8 ')) CLIENT.RECV (1024) # fix sticky Package Issue 18 # send file 19 withOpen ("1.jpg", ' RB ') asF:20 forLineinchF:21 Client.sendall (line) client.close () ftpclientFour. Solving the problem of sticky bagFor the above description of the third FTP upload, to solve the problem of sticky packets, when we upload a file, the first upload his size, when we upload the size to write a sentence to accept the statement, and the server side after accepting the file size to send us immediately sent a data to confirm, So that we can perfect the data to drink the size of the split open.
    Source: Blog Park

    How does a socket in Python work?

    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.