Python Sockets basic usage

Source: Internet
Author: User

Python sockets basic Use socket

Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and applications usually make requests to the network through "sockets" or respond to network requests, which can be considered a data structure and interface for a computer network. It is the foundation of network programming

Sockets originated in the UNIX system, the first use of communication between the process and a computer, the current socket is divided into two types, based on file type and network-based. One of the hosts is communicating between processes through a file-based socket (Af_unix or af_local). There is also a network-based, available for communication between different hosts (Af_inet and Ap_inet6), Af_inet is for IPV4, and Af_inet6 is for IPV6.

Sockets are also divided into connection-oriented and non-connected:

    1. The first is the TCP type socket, which needs to establish a connection before communication, the connection is more reliable, the type of socket used is SOCK_STREAM,TCP Transmission Control Protocol, which is often used in conjunction with the IP protocol, called the TCP-IP protocol
    2. The second mainly refers to the type of UDP socket, no need to connect to communicate, all faster, but not high reliability. And the data is the entire send, not divided into small pieces. The socket type used is the SOCK_DGRAM,UDP protocol, which is also commonly used with IP protocols
The socket module in Python

Basic steps for using sockets:

    • Creating sockets

      socket(socket_family, socket_type, protocol)#socket_family 就是指套接字家族可以是AF_VNIX或AF_INET#socket_type 就是指套接字类型,即SOCK_STREAM或SOCK_DGRAM#protocol 是协议,默认为0,一般不填
    • Create TCP/IP or UDP/IP sockets
      1. Create a TCP/IP socket

        sockettcp = socket.socket(AF_INET, SOCK_STREAM)
      2. Create UDP/IP sockets

        socketucp = socket.socket(AF_INET, SOCK_DGRAM)
    • Common functions for sockets

Name of function Description
Server sockets
Bind ((hostname, port)) Bind address (note here is Ganso) to socket
Listen () Turn on TCP snooping
Accept () Passive accepting of client connections (blocking)
Client sockets
Connect ((hostname, port)) Initializing a TCP server connection
CONNECT_EX () Extended version of Connect (), which returns an error code instead of an exception when an error occurs
Common sockets
Recv () Receiving data from TCP
Send () Sending TCP data
Sendall () Send the full TCP data
Recvfrom () Receive UDP data
SendTo () UDP data occurs because there is no connection, so here you specify the destination to send
Getpeername () Connect to the remote address of the current socket
GetSockName () Current socket Address
GetSockOpt () Get the parameters of a socket
SetSockOpt () Set parameters for sockets
Close () Close socket
module-oriented socket functions
Setblocking () Set whether the socket is blocking mode
SetTimeout () To set the timeout period for blocking socket operations
GetTimeout () Get the timeout for blocking socket operations
File-oriented socket functions
Fileno () File descriptor for sockets
Makefile () Create a file object associated with the socket
Create a TCP server and client

Basic steps for creating a TCP server

    1. Create sockets and BIND addresses
    2. Start listening for connections
    3. Receive links and send data
    4. Close socket

The code is as follows:

ImportSockethost =‘‘#空字符串标示127.0.0.1PORT =3214sk =socket. socket () # use IPV4 and Tcpsk.listen (5) cli, addr = Sk.accept () # wait for connection (blocking), will block here before the connection arrives print  "Client Addr:", Addrwhile true:data = Cli. Recv (1024) if not data: break print  "recieve Data:", Data.decode ( Span class= "hljs-string" > ' utf-8 ') CLI. send (data) CLI. close ()             

Basic steps for creating a TCP client

    1. Create sockets, connect to server
    2. Send and receive data
    3. Close socket
Import socketHOST = '127.0.0.1 'PORT =361°SK = Socket.socket ()try:sk.connect ((host, PORT)) data = "Hello" while  Data:sk.sendall (data) data = Sk.recv (1024x768) print " recv data: ", data data = Raw_input (' please input message\ n ') except socket.error as err:print err Finally:sk.close ()              

The client here can only send a message to the server, and the server will receive the message and resend it back to the client.

Creating UDP servers and clients

Basic steps for creating a UDP service side

    1. Create sockets and BIND addresses
    2. Start listening for connections
    3. Send and receive data
    4. Close socket
Import socketHOST = ' 'PORT =3214SK = Socket.socket (socket).af_inet, Socket. Sock_dgram) Sk.bind ((HOST, PORT))data = True while data: data, addr = Sk.recvfrom (1024x768) if data = = B ' Bye ': Break print "recieve data:", data.decode ('utf-8 ') sk.sendto (data, addr)  Sk.close ()                

Basic steps for creating a UDP client

    1. Creating sockets
    2. Send and receive data
    3. Close socket
Import socketHOST = '127.0.0.1 'PORT =361°SK = Socket.socket (socket).Af_inet, Socket.SOCK_DGRAM)data = ' Hello 'Whiledata:sk.sendto ( data, (host, port)) if data = =" Bye ": Break  data, addr = Sk.recvfrom (1024x768) print  "RECV data:", data data = Raw_input ( ' please message:\n ') sk.close () # tcpclient differs from udpclient # Differences when establishing sockets # TCP requires link server # send and receive data methods different      

The difference here with TCP is not to establish a connection, the client just send and receive messages, and do not establish a connection with the server

Python Sockets basic usage

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.