Learn python from scratch Eighth week: Network Programming Basics (socket)

Source: Internet
Author: User
Tags server port

Socket network programming one, Socket programming (1) Socket method Introduction
    • Sockets are an abstract concept of network programming. Usually we use a socket to indicate "open a network link", while opening a socket needs to know the destination computer's IP address and port number, and then specify the protocol type.
    • Sockets are the endpoints of a two-way communication channel. Sockets may be in the process of communicating, between processes on the same machine, or between different computers
    • To create a socket, you must use the Socket.socket () method of the socket module
    • General syntax in the socket module:

s = Socket.socket (socket_family,socket_type,protocol=0)

(3) Introduction to TCP
    • Most connections are reliable TCP connections. When you create a TCP connection, you initiate a connected call to the client, and the passive response is called the server
    • For example, in the browser to visit Sina, our own computer is the client, the browser will be active to Sina's server to initiate the connection. If all goes well, Sina's server accepts our connection, a TCP connection is established, the subsequent communication is to send Web content
(4) TCP Programming Demo-Client
    • To create a TCP connection-based socket, the code demonstrates:
1 Import Socket 2 3 s = socket.socket (socket.af_inet,socket. SOCK_STREAM)4 s.connect (('www.sina.com.cn', 80))

    • After establishing a TCP connection, you can send a request to the server asking for the contents of the first page, the text format must conform to the HTTP standard, then receive the data returned by the server, and finally close the connection
(5) TCP Programming Demo-Server
    • Server programming is more complex than client-side programming, where the server process first binds a port and listens for connections from other clients. If a client is connected, the server establishes a socket connection to the client, and the subsequent communication is connected by the socket.
    • Write a simple server program that receives a client connection, sends a string of strings sent by the client to the back, and the code shows:
1 ImportSocket2 3Host ='Locakhost'      #IP address of the listener4Port = 8888#ports to listen on5s = Socket.socket (socket.af_inet,socket. SOCK_STREAM)#set up sockets6S.bind (Host,port)#binding IP addresses and ports7S.listen (5)#Start listening .8CONN,ADDR = S.accept ()#accept a new connection9data = CONN.RECV (1024)#Receive client stringTenConn.sendall (data+'Hello')#send a string to the client

    • It is important to note that the same port, after being bound by a socket, cannot be bound by another socket.
(6) Introduction of UDP
    • TCP is to establish a reliable connection, and both sides of the communication can send data in the form of a stream. The relative tcp,udp is a non-connection oriented protocol
    • When using the UDP protocol, you do not need to establish a connection, just need to know the other side's IP address and port number, you can directly send packets. But it's not clear that you can get there.
    • Although it is unreliable to transmit data with UDP, it has the advantage of being faster than TCP, and can use UDP protocol for data that does not require reliable arrival.
(7) UDP programming Demo
    • Data is transmitted over the UDP protocol. Like TCP, both sides of the communication using UDP are also divided into clients and servers. The server first needs to bind the port, and the code demonstrates:
1 s = socket.socket (socket.af_inet,socket. SOCK_DGRAM)2 s.bind (('127.0.0.1', 9999))   # Port Binding 

    • When a client uses UDP, it still creates a UDP-based socket, but does not need to call connect () to send data directly to the server via SendTo (), and the code demonstrates:
1 s = socket.socket (socket.af_inet,socket. SOCK_DGRAM)2 for in ['Michael','Tracy  ','Sarah':3     s.sendto (data)

    • It is important to note that the server-bound UDP port and TCP port do not conflict, and UDP 9999 port and TCP 9999 port can be bound separately
Two, TCP programming example

Sockets are an abstract concept of network programming. Usually we use a socket to indicate "open a network link", while opening a socket needs to know the destination computer's IP address and port number, and then specify the protocol type.

    • Client

For example, when we visit Sina in a browser, our own computer is the client, and the browser initiates a link to Sina's server. If all goes well, Sina's server receives our connection, a TCP connection is established, and the subsequent communication is to send the Web content.

So, we're going to create a TCP connection-based socket that can do this:

1 # Importing the socket library 2 Import Socket 3 # Create a socket: 4 s = socket.socket (socket.af_inet,socket. SOCK_STREAM)5#  Establish connection 6 s.connect ('  www.sina.com.cn', 80))

When creating a socket, af_inet specifies that the IPV4 protocol is used, and if a more advanced IPv6 is used, it is specified as Af_inet6. SOCK_STREAM specifies that a stream-oriented TCP protocol is used, so that a socket object is created successfully, but no connection has been established.

To proactively initiate a TCP connection, the client must know the IP address and port number of the server. The IP address of the Sina website can be automatically converted to the IP address with the domain name www.sina.com.cn, and the standard port 80 of the Web service.

So our code to connect to the Sina server is as follows:

s = Connect ('www.sina.com.cn', 80)

Note The parameter is a tuple that contains the address and port number.

After establishing the TCP connection, we can send a request to the Sina server and ask to return the contents of the homepage:

# Send data:s.send ('get/http/1.1\r\nhost:www.sina.com.cn\r\nconnection:close\r\n\r\n' )

A TCP connection creates a bidirectional channel in which both parties can send data to each other. However, who first sent after the hair, how to coordinate, according to the specific agreement to decide. For example, the HTTP protocol specifies that the client must send a request to the server before the server sends the data to the client.

Send the text format must conform to the HTTP standard, if the format is not a problem, then you can receive the data returned by Sina server:

1 #Receive data:2Buffer = []3  whileTrue:4     #receive up to 1K bytes at a time:5D = S.RECV (1024)6     ifD:7 Buffer.append (d)8     Else:9          BreakTendata ="'. Join (Buffer)

When the data is received, the recv (max) method is called, which receives the specified number of bytes at a time, so it is received repeatedly in a while loop until recv () returns empty data, indicating that the receive is complete and exits the loop.

When we have finished receiving the data, call the Close () method to close the socket so that a complete network communication is over:

# Close Connection s.close ()

The data received include the HTTP header and the Web page itself, we just need to separate the HTTP header and Web page, the HTTP header print out, the content of the Web page to save to the file:

header,html = Data.split ('\r\n\r\n', 1)print  header#  Write the received data to a file:with open ('sina.html','wb'  ) as F:    f.write (HTML)

Now, just open the sina.html file in the browser, you can see the homepage of Sina.

    • Server

Server programming is a bit more complicated than client programming.

The server process first binds a port and listens for connections from other clients. If a client connects, the server establishes a socket connection to the client, and the subsequent communication is connected to the socket.

Therefore, the server opens a fixed port (for example, 80) to listen, creating the socket connection for each client connection. Because the server opens a fixed port (for example, 80) to listen, each client connection is created to create the socket connection. Because the server will have a large number of connections from the client, the server is able to differentiate between which client and which clients the socket connection is bound to. A socket relies on 4 items: server address, server port, client address, client port to uniquely identify a socket.

However, the server also needs to respond to multiple client requests at the same time, so each connection requires a new process or a new thread to handle, or the server can only serve one client at a time.

Let's write a simple server program that receives a client connection and sends a string of strings from the client to a hello and send it back.

First, create a socket based on the IPV4 and TCP protocol:

s = Socket.socket (socket.af_inet,socket. SOCK_STREAM)

Then we want to bind the listening address and port. The server may have more than one network card, can be bound to the IP address of a network card, you can 0.0.0.0 bind to all network addresses, you can also use 127.0.0.1 to bind to the native address. 127.0.0.1 is a special IP address that represents the native address, and if bound to this address, the client must be running at the same time in order to connect, that is, the external computer cannot connect.

The port number needs to be specified beforehand. Because we write this service is not standard service, so with 9999 this port number. Note that a port number less than 1024 must have administrator privileges to bind:

# Listening Port s.bind ('127.0.0.1', 9999)

Immediately after that, call the Listen () method to start listening on the port, and the incoming parameter specifies the maximum number of waiting connections:

S.listen (5)print'waiting for connection ... '

Next, the server program passes a permanent loop to accept the connection from the client, and accept () waits for and returns a client connection:

 while TAG:     # accept a new connection    CONN,ADDR = s.accept ()    #  creates a new thread to handle TCP connections     t = Threading. Thread (target=tcplink,args=(conn,addr))     T.start ()

Each connection must create a new thread (or process) to handle, or the single thread cannot accept connections from other clients during the process of processing the connection:

defTcplink (conn,addr):Print('Accept New Connection form {0}'. Format (addr)) Conn.send ('welcome!')     whileTrue:data= CONN.RECV (1024) Time.sleep (1)        ifdata = ='Exit' or  notData: BreakSocket.send ('hello,{0}!'. Format (data)) Conn.close ()Print('Connection from {0} closed.'. Format (addr))

After the connection is established, the server first sends a welcome message and then waits for the client data, plus a hello to send to the client. If the client sends the exit string, the connection is closed directly

To test this server program, we also need to write a client program:

  

s =Socket.socket (Socket.af_inet,socket. SOCK_STREAM)#To establish a connection:S.connect (('127.0.0.1', 9999))#To receive a welcome message:PrintS.RECV (1024) forDatainch['Michael','Tracy','Sarah']:    #Send data:s.send (data)PrintS.RECV (1024) S.send ('Exit') S.close ()

Then we open two command-line windows, one running the server program, the other running the client program, you can see the effect.

Note that the client program runs out, and the server program will run forever, you must press CTRL + C to exit the program.

    • Summary

Socket programming with TCP protocol is very simple in Python, for the client, to actively connect to the server IP and the specified port, for the server, to first listen to the port, and then, for each new connection, create a thread or process to process. Typically, the server program will run indefinitely.

The same port, after being bound by a socket, cannot be bound by another socket.

Learn python from scratch Eighth week: Network Programming Basics (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.