Network programming in Python-socket module, creating a TCP server, creating a TCP Client

Source: Internet
Author: User

Network Programming in Python

first, socket () Module

Second, create a TCP server

Third, create a TCP client

First,socket module

Socket:

Sockets are originally created for applications on the same host, allowing a program (aka one process) running on the host to communicate with another running program. This is called interprocess communication (Inter processcommunication, IPC). There are two types of sockets: file-based and network-oriented. In general, Python supports only the Af_unix, Af_netlink, AF_TIPC, and af_inet families.

socket () module function to create a socket, you must use the Socket.socket () function, It's general syntax:

  

Where socket_family is Af_unix or af_inet (as previously described), Socket_type is Sock_stream or Sock_dgram (also described earlier). Protocol is usually omitted and defaults to 0.

therefore, in order to create a TCP/IP socket, you can call Socket.socket () in the following way.

  


Similarly, in order to create a UDP/IP socket, the following statement needs to be executed.

  

because there are many socket module properties, it is acceptable to use the "from module Import *" Method at this point, but this is only one of the exceptions. If you use "from socket import *", then we introduce the socket attribute into the namespace. While this may seem a bit of a hassle, the code will be greatly shortened in this way, as:

  

             Form Query

Name Description
S.send () Sending a TCP message
S.sendall () Send a TCP message in full
S.recvfrom () Receiving UDP messages
S.recvfrom_into () Receives a UDP message to the specified buffer
S.sendto () Send UDP message
S.getpeername () Connect to the remote address of the socket (TCP)
S.getsockname () Address of the current socket
S.getsockopt () Returns the value of the given socket option
S.setsockopt () Sets the value of a given socket option
S.shutdown () Close connection
S.close () Close socket
S.detach ()

Closes the socket without closing the file descriptor, returns the file descriptor

S.ioctl ()

Mode of control sockets (Windows only) blocking-oriented socket methods

S.setblocking () To set blocking or non-blocking mode for sockets
S.settimeout () To set the timeout period for blocking socket operations
S.gettimeout ()

Gets the time-out of a blocking socket operation for a file-oriented socket method

S.makefile () To create a file object Data property associated with a socket
S.family Socket family
S.proto Socket protocol

Second, create a TCP server

Create a generic The generic pseudo-code of the TCP server , and then a general description of the meaning of the code.

SS = socket ()                     # Create server Socket Ss.bind ()                           # Socket with address binding ss.listen ()                         # Listener Connection inf_loop:                          # server infinite loop        cs = ss.accept ()           # Accept Client Connection        Comm_loop:                # Communication Loop              Cs.recv ()/cs.send ()  # Dialog (receive/Send)        cs.close ()                   # Close the client socket Ss.close ()                      # Close Server sockets # (optional)            

All sockets are created by using the Socket.socket () function. Because the server needs to occupy a port and wait for client requests, they must be bound to a local address. Because TCP is a connection-oriented communication system, some infrastructure must be installed before the TCP server begins operation. In particular,the TCP server must listen for (incoming) connections. Once the installation process is complete, the server can start its infinite loop.

The script then creates a TCP server that accepts messages from the client and then sends the message back to the client with a timestamp prefix

The 6~13 row HOST variable is blank, which is the identity of the Bind () method, indicating that it can use any available address. We also chose a random port number, and the port number does not appear to be in use or reserved by the system. Also, for the application, set the buffer size to 1KB. This capacity can be changed based on network performance and program needs. the parameter of the Listen () method is the maximum number of incoming connection requests before the connection is forwarded or rejected. On Line 11, a TCP server socket (tcpsersock) is assigned, followed by a call to bind the socket to the server address and to turn on the TCP listener.

Line 15~28 Once you enter the infinite loop of the server, we wait (passively) for the client to connect. When a connection request appears, we enter the conversation loop where we wait for the message sent by the client. If the message is blank, this means that the client has exited, so at this point we will jump out of the conversation loop, close the current client connection, and wait for another client to connect. If you do get a message sent by the client, it is formatted and returns the same data, but the current timestamp prefix is added to the data.

Third, create a TCP client

It is much simpler to create a client than a server.
such as:

CS = socket ()               # Create client Socket Cs.connect ()                # Try to connect to server Comm_loop:                  # Communication Loop         Cs.send ()/cs.recv ()     # Dialog (send /receive) Cs.close ()                  # Close the client socket  

As mentioned earlier, all sockets are created using Socket.socket (). However, once the client has a socket, it can create a connection to the server directly using the Connect () method of the socket. Once the connection is established, it can participate in a conversation with the server. Finally, once the client has completed its transaction, it can close the socket and terminate the connection.

The script then creates a TCP client that prompts the user to enter a message sent to the server side and receives the same message that was returned from the server with the timestamp prefix added, and then presents the result to the user.

Line 1th to 3rd imports all properties from the socket module after the UNIX startup line. The 5th to 11th row of host and port variables refers to the server's hostname and port number. Because you are running tests on the same computer (in this case), host contains the local hostname (if your server is running on a different host, you need to modify it accordingly). Port number port should be exactly the same as the one you set for the server (otherwise, you will not be able to communicate). Also, set the buffer size to 1KB. The TCP client sockets (Tcpclisock) are assigned on line 10th and are then actively invoked and connected to the server. The 13th to 23rd line of the client also has an infinite loop, but that doesn't mean it will run like a server loop forever. The client loop will jump out in the following two conditions: the user has no input (line 14th to 16th), or the server terminates and the call to the Recv () method fails (line 18th to 20th). Otherwise, under normal circumstances, the user enters some string data and sends the data to the server for processing. The client then receives a timestamp-added string and displays it on the screen. in this code snippet, the local host needs to be modified to its IPV6 address ":: 1" while requesting the socket's AF_INET6 family. If you combine the changes in tstclnt3.py and tstclntv6.py, you will get a Python 3 version of the IPV6 TCP client.

 

 

  

 

 

 

  

Network programming in Python-socket module, creating a TCP server, creating a TCP Client

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.