Learn python eighth week from scratch: Detailed Network Programming Basics (socket) _python

Source: Internet
Author: User
Tags server port in python

One, socket programming

(1) Introduction to Socket method

    • Socket is an abstract concept of network programming. Usually we use a socket to indicate "open a network link", and opening a socket requires knowing the IP address and port number of the target computer, and then specifying the protocol type.
    • A socket is the endpoint of a two-way communication channel. Sockets may be in the process of communication, 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 creating a TCP connection, it is called the client that initiates the connection, and the passive response to the connected call server

For example, when visiting Sina in the browser, our own computer is the client, the browser will initiate the connection to Sina's server. If all goes well, Sina's server accepts our connection, a TCP connection is established, the following communication is to send the content of the Web page

(4) TCP Programming Demo-Client

To create a socket based on a TCP connection, the code demonstrates:

 Import socket
 
 s = socket.socket (socket.af_inet,socket. SOCK_STREAM)
 s.connect ((' www.sina.com.cn ',))

After establishing a TCP connection, you can send a request to the server, request the content of the first page, send the text format must meet 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 programming, and 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 subsequent communications are connected by this socket.

Write a simple server program, it receives the client connection, the client sent over the string plus hello again sent back, code demo:

 Import socket
 
 Host = ' locakhost '   #监听的IP地址
 port =       #监听的端口
 s = Socket.socket (socket.af_inet,socket. SOCK_STREAM)  #建立套接字
 s.bind (host,port)    #绑定IP地址和端口
 s.listen ()       #开始监听
 conn,addr = s.accept () #接受一个新连接
 data = CONN.RECV () #接收客户端字符串
 conn.sendall (data+ ' Hello ') #发送字符串给客户端

It should be noted that the same port, is bound by a socket, you can not be another socket binding

(6) Introduction to UDP

    • TCP is a reliable connection, and both sides of the communication can send data in the form of a stream. Relative tcp,udp is oriented to connectionless protocol
    • When using the UDP protocol, you do not need to establish a connection, only need to know each other's IP address and port number, you can send packets directly. However, it is not clear whether it can be reached.
    • Although it is unreliable to transmit data with UDP, its advantage is that it is faster than TCP and can use UDP for data that does not require reliable arrival

(7) UDP programming Demo

Transmits data through the UDP protocol. Like TCP, both sides of communication using UDP are divided into clients and servers. The server first needs to bind the port, the code demonstrates:

 s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)
 s.bind ((' ... ',))  #端口绑定

When a client uses UDP, it still creates a socket based on UDP, but does not need to call connect (), sends data directly to the server via SendTo (), and the code shows:

 s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)
 for data in [' Michael ', ' Tracy ', ' Sarah ']:
   s.sendto (data)

Note that server-bound UDP ports and TCP ports do not conflict, UDP 9999 ports and TCP 9999 ports can be bound separately

Second, examples of TCP programming

Socket is an abstract concept of network programming. Usually we use a socket to indicate "open a network link", and opening a socket requires knowing the IP address and port number of the target computer, and then specifying the protocol type.

Client

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

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

 # import Socket library Import
 Socket
 # Create a socket:
 s = Socket.socket (socket.af_inet,socket. SOCK_STREAM)
 # Establish Connection
 S.connect ((' www.sina.com.cn ',))

When you create a socket, af_inet specifies that the IPV4 protocol be used and, if you want to use a more advanced IPv6, specify AF_INET6. SOCK_STREAM Specifies the use of a stream-oriented TCP protocol, so that a socket object is created successfully, but no connection has been established.

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

Therefore, our code to connect the Sina server is as follows:

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

Note that the parameter is a tuple, containing the address and port number.

After establishing the TCP connection, we can send the request to the Sina server, request to return the content of the first page:

# 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 two-way channel in which both parties can send data to each other. But who sends first, how to coordinate, according to the specific agreement to decide. For example, the HTTP protocol requires the client to send a request to the server before sending data to the client before the server receives it.

The text format you send must conform to the HTTP standard, and if the format is OK, you can then receive the data returned by the Sina server:

 # Receive data:
 buffer = [] While
 True:
   # receive up to K bytes per time:
   d = srecv ()
   if D:
     bufferappend (d)
   else:
     Break
   data = ' Join (buffer)

When receiving data, call the Recv (max) method, which receives a maximum of the specified number of bytes at a time, so that it is repeatedly received in a while loop until recv () returns empty data, indicating that the reception is complete, exiting the loop.

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

# Close Connection
s.close ()

The data received includes HTTP headers and the Web page itself, we only need to separate HTTP headers and Web pages, the HTTP header printed out, the content of the Web page saved to the file:

header,html = Data.split (' \r\n\r\n ', 1)
Print Header
# writes the received data to the file: with
open (' sina.html ', ' WB ') as F:
  F.write (HTML)

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

Server

Server programming is a bit more complex than client programming.

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 with the client, and subsequent communications are connected by this socket.

Therefore, the server will open a fixed port (such as 80) listening, each to a client connection, create the socket connection. Because the server opens a fixed port (for example, 80) listening, the socket connection is created on each client connection. Because the server will have a large number of connections from the client, the server should be able to differentiate between which client a socket connection is bound to. One socket relies on 4 items: server address, server port, client address, client port to uniquely determine 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 process, otherwise, the server can only serve one client at a time.

Let's write a simple server program that receives a client connection, sends a string from the client and sends it back.

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

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

Then, we're going to bind the listener's address and port. The server may have more than one network card, can bind to the IP address of a certain network card, also can 0.0.0.0 bind to all network address, also can bind to native address with 127.0.0.1. 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 on the computer simultaneously to connect, that is, external computers cannot be connected.

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

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

Immediately thereafter, the call to the Listen () method starts the listening port, and the incoming parameters specify the maximum number of pending connections:

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

Next, the server program accepts a connection from the client through a permanent loop, and accept () Waits and returns a client connection:

While TAG:
  # accept a new connection
  conn,addr = s.accept ()
  # Create 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 process it, otherwise, a single thread cannot accept connections from other clients during processing of the connection:

def tcplink (conn,addr):
  print (' Accept new connection form {0} '. Format (addr))
  conn.send (' welcome! ')
  While True:
    data = CONN.RECV (1024)
    time.sleep (1)
    if data = "exit" or "not" data:
    break Socket.send (' hello,{0}! '. Format (data)
  conn.close ()
  print (' Connection from {0} closed. '). Format (addr))

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

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

s = Socket.socket (socket.af_inet,socket. SOCK_STREAM)
# Establish connection:
S.connect ((' 127.0.0.1 ', 9999)
# receive Welcome message:
Print S.RECV (1024) for
data in [' Michael ', ' Tracy ', ' Sarah ']:
  # Send data:
  s.send (data)
  print S.RECV (1024)
s.send (' exit ')
S.close ()

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

It should be noted that the client program is finished running, and the server program will run forever, you must press CTRL + C to exit the program.

Summary

Using the TCP protocol for socket programming in Python is very simple, for the client, to actively connect the server's IP and specified port, for the server, first listen to the port, and then, for each new connection, create a thread or process to handle. Typically, server programs run indefinitely.

Once the same port is bound by a socket, it cannot be bound by another socket.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.