Python socket, pythonsocket

Source: Internet
Author: User

Python socket, pythonsocket

Python network programming mainly supports two network protocols: TCP and UDP. Both protocols are processed through the Socket programming abstraction. Socket originated from Unix and is similar to the existence of files. It can perform I/O, open, close, and other operations like files. The most important thing is that it can implement inter-process communication between different hosts on the network, therefore, Socket is the most basic content in any network communication.

Creating a socket in Python is simple:

import sockets = socket.socket(family, type)
Address Family

Family is the address family, which specifies the network protocol to be used, mainly used:

  • AF_INET: IPv4 protocol (TCP, UDP)
  • AF_INET6: IPv6 protocol (TCP, UDP)
  • AF_UNIX: UNIX domain protocol for communication between processes on the same machine
Socket Type

Type is the socket type and specifies the communication type used in the given protocol group:

  • SOCK_STREAM: used for TCP
  • SOCK_DGRAM: used for UDP

Both TCP and UDP are based on the Client/Server programming model, so Socket programming is also divided into Client and Server. Take TCP as an example:

TCP client Programming

To obtain the IP address of the remote host, you can use the gethostbyname () method provided by the socket Standard Library:

>>> import socket>>> socket.gethostbyname('www.baidu.com')'115.239.211.112'

The socket instance s can be used on the client in the following ways:

  • S. connect (addr): connects to the server socket. The addr format depends on the address family. For IPv4, It is a tuple containing IP addresses and ports (host, port ). If the connection fails, a socket. error is returned.
  • S. sendall (string): If all data is sent successfully, None is returned. If the data fails, an exception is thrown.
  • S. recv (bufsize): receives data. bufsize specifies the maximum data size received.
  • S. close (): close socket

OK. Now you can use socket to send an HTTP GET request to the remote host:

#-*-Coding: UTF-8-*-import sockets = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # create a socket host = 'www .baidu.com 'port = 80ip = socket. gethostbyname (host) # obtain ips. connect (ip, port) # establish a connection message = 'get/HTTP/1.1 \ r \ n \ r \ n' s. sendall (message) # Send GET request r = s. recv (4096) # receive data print rs. close () # close the socket

Return Value:

HTTP/1.1 302 Moved TemporarilyDate: Wed, 10 Jan 2018 18:56:45 GMTContent-Type: text/htmlContent-Length: 225Connection: Keep-AliveLocation: http://www.baidu.com/search/error.htmlServer: BWS/1.1X-UA-Compatible: IE=Edge,chrome=1BDPAGETYPE: 3Set-Cookie: BDSVRTM=0; path=/

We can implement our own server.

TCP Server programming

The Socket instance has the following methods related to Server programming:

  • S. bind (addr): addr is also a (host, port) form tuples, bind the socket to a specific address and port. An empty string represents any address, and 'broadcast' can be used to send broadcast information.
  • S. listen (backlog): starts listening for connections. backlog is the maximum number of pending connections.
  • S. accept: returns the tuples (conn, addr). conn is a new socket that can be used to send and receive data. Addr is the socket address of the client.
  • S. recv (), s. sendall (), and s. close () are the same as those of the client.

Now write a server that sends the information sent from the client back:

#-*-Coding: UTF-8-*-import socketimport sys HOST = ''PORT = 8088 s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) s. bind (HOST, PORT) s. listen (5) print 'start to listen to 'conn, addr = s. accept () print 'connectedwith' + addr [0] + ':' + str (addr [1]) data = conn. recv (1, 1024) conn. sendall (data) conn. close () s. close ()

Run:

>>> Start listening

The server started listening for the connection. Modify the client program you just wrote:

#-*-Coding: UTF-8-*-import sockets = socket. socket (socket. AF_INET, socket. SOCK_STREAM) host = 'localhost' port = 8088s. connect (host, port) # establish a connection message = 'get/HTTP/1.1 \ r \ n \ r \ n' s. sendall (message) # Send GET request r = s. recv (4096) # receive data print rs. close () # close the socket

Run, connect to the local server, and the server output:

>>> Start listening for Connected with 127.0.0.1: 60933

Connection successful. Client output:

>>> GET / HTTP/1.1

The sent message is returned.

This is the simplest server. The above server can only process one connection. This is obviously not what we want to see. Keep running:

#-*-Coding: UTF-8-*-import socketimport sys HOST = ''PORT = 8088 s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) s. bind (HOST, PORT) s. listen (5) print 'start listening 'while True: conn, addr = s. accept () print 'connectedwith' + addr [0] + ':' + str (addr [1]) data = conn. recv (1, 1024) conn. sendall (data) conn. close () s. close ()

Now you can use the client for unlimited connection:

>>> Start listening for Connected with 127.0.0.1: 61240 Connected with 127.0.0.1: 61242 Connected with 127.0.0.1: 61245 Connected with 127.0.0.1: 61250
Server-side multi-thread processing connection

Although the server can process unlimited connections, it can only process them one by one. Subsequent client connections can only send data after the previous connection is complete. To process multiple connections at the same time, you can use multiple threads. After receiving a new connection, the server starts a thread to process the new connection, and the main thread establishes the next connection.

Server:

#-*-Coding: UTF-8-*-import socketimport threadingHOST = ''PORT = 8088 s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) s. bind (HOST, PORT) s. listen (5) print 'start to listen to 'def runThread (conn): data = conn. recv (1024) print data conn. sendall (data) conn. close () while True: conn, addr = s. accept () print 'connectedwith' + addr [0] + ':' + str (addr [1]) t = threading. thread (target = runThread, args = (conn,) t. daemon = True t. start ()

The client starts multiple connections:

# -*- coding: utf-8 -*-import socketimport timeimport threadingdef run():    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    host = 'localhost'    port = 8088    s.connect((host, port))     message = 'GET / HTTP/1.1\r\n\r\n'    s.sendall(message)     print s.recv(4096)        s.close()                if __name__ == '__main__':    for i in xrange(4):        t = threading.Thread(target=run)        t.start()

Run:

Start listening to Connected with 127.0.0.1: 61772GET/HTTP/1.1 Connected with 127.0.0.1: 61773GET/HTTP/1.1 Connected with 127.0.0.1: 61774GET/HTTP/1.1 Connected with 127.0.0.1: 61775GET/HTTP
UDP Programming

The difference between UDP and TCP is that UDP does not need to establish a connection.

S. recvfrom () and s. sendto () method, the former and s. the recv () is the same, but the returned (data, addr) tuples. addr is the socket address of the data sender, and the remote address to be sent must be added when the latter sends data.

Server:

#-*-Coding: UTF-8-*-import sockets = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) s. bind ('', 10000) while True: data, addr = s. recvfrom (1024) print 'received % s connection' % str (addr) s. sendto (data, addr)

Client:

# -*- coding: utf-8 -*-import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.sendto('Hello World', ('localhost', 10000))r, addr = s.recvfrom(1024)print rs.close()

Run:

>>> Received connections ('127. 0.0.1 ', 127) >>> Hello World

  

 

  

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.