Python Network Programming Study Notes (III): socket network server

Source: Internet
Author: User

1. TCP connection Establishment Method

Generally, two steps are required for the client to establish a TCP connection, and four steps are required for the server process. For details, see the comparison below.

Procedure TCP client TCP Server
Step 1 CreateSocketObject CreateSocketObject
Step 2 CallConnect ()Establish a connection with the server SetSocketOptional)
Step 3 None Bind to a port (or a specified Nic)
Step 4 None Listener connection

The following describes how to establish these four steps:

Step 1: Create a socket object: This is the same as the client, but it is still:

S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)

Step 2: Set and obtain socket options

Python defines setsockopt () and getsockopt (). One is the setting option, and the other is to get the setting. Here we mainly use setsockopt (). The specific structure is as follows:

Setsockopt (level, optname, value)

Level defines which option will be used. It is usually SOL_SOCKET, which indicates the socket option in use. It can also set protocol options by setting a special protocol number. However, for a given operating system, most protocol options are clear, so for simplicity, they are rarely used for apps designed for mobile devices.

The optname parameter provides special options. The setting of available options varies slightly depending on the operating system. If SOL_SOCKET is selected for level, the following table lists some common options:

Option

Meaning

Expected Value

SO_BINDTODEVICE

EnableSocketValid only for a special network interface (NIC. Maybe it cannot be a mobile portable device

A string indicates the device name or an empty string. The default value is returned.

SO_BROADCAST

Allows the broadcast address to send and receive packets. Only pairUDPValid. How to send and receive broadcast packets

Boolean integer

SO_DONTROUTE

It is prohibited to send information packets out of routers and gateways. This is mainly used on Ethernet for security purposesUDPCommunication Method. No matter what the destination address isIPAddress to prevent data from leaving the local network

Boolean integer

SO_KEEPALIVE

EnableTCPThe communication information package maintains continuity. When no information is transmitted, the information packets can be confirmed by both parties that the connection is maintained.

Boolean integer

SO_OOBINLINE

We can regard the received abnormal data as normal data, that is, it will pass a standard pairRecv ()To receive the data.

Boolean integer

SO_REUSEADDR

WhenSocketThe local end is usedSocketCan be reused immediately. Generally, it can be reused only after the system has been defined for a period of time.

Boolean integer



This section describes how to use the SO_REUSEADDR option:

S. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1) Here value is set to 1, which indicates to mark SO_REUSEADDR as TRUE. The operating system will release the port of the server immediately after the server socket is closed or the server process is terminated, otherwise, the operating system retains the port for several minutes.

The following method provides a list of socket options supported by python in the system:

Copy codeThe Code is as follows:
Import socket
Solist = [x for x in dir (socket) if x. startswith ('so _ ')]
Solist. sort ()
For x in solist:
Print x

Step 3: bind a socket

Binding requires a port number for the server.

S. bind (host, port), where host is the Server ip address, usually empty, can also be bound to a specific ip address. Port is the Port number.

Step 4: Listen for connections.

Use the listen () function to connect listeners. This function has only one parameter, indicating how many pending connections are allowed to wait in the queue when the server actually processes the connection. As an agreement, many people set it to 5. For example, s. listen (5)

2. Simple TCP server instance
 
This creates a simple TCP server and client.

Server: TCP response server. When a connection is established with the client, the server displays the Client ip address and port, and the received client information and 'I get it! 'Send to the client, and wait for a new message to be input to the client.

Client: TCP client. First, enter the Server IP address, and then enter the information. Press enter to obtain the information returned by the server. Then, wait for the server to send the information to it and exit.

The Code is as follows:
Server: tcpserver. py

Copy codeThe Code is as follows:
#-*-Coding: cp936 -*-
# Tcp response server. When a connection is established with the client, the server displays the Client ip address and port, and the received client information and 'I get it! 'Send to the client, and wait for a new message to be input to the client.
##@ Xiao Wuyi
Import socket, traceback
Host =''
Port = 12345
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
S. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1)
S. bind (host, port ))
S. listen (1)

While 1:
Try:
Clientsock, clientaddr = s. accept ()
Except t KeyboardInterrupt:
Raise
Except t:
Traceback. print_exc ()
Continue
Try:
Print "connection from:", clientsock. getpeername ()
While 1:
Data = clientsock. recv (4096)
If not len (data ):
Break
Print clientsock. getpeername () [0] + ':' + str (data)
Clientsock. sendall (data)
Clientsock. sendall ("\ nI get it! \ N ")
T = raw_input ('input the word :')
Clientsock. sendall (t)
Except T (KeyboardInterrupt, SystemExit ):
Raise
Except t:
Traceback. print_exc ()

Try:
Clientsock. close ()
Except t KeyboardInterrupt:
Raise
Except t:
Traceback. print_exc ()

Client: tcpclient. py

Copy codeThe Code is as follows:
#-*-Coding: cp936 -*-
# For the tcp client, first enter the Server IP address, and then enter the information. After you press enter, the server will return the information, and then exit after the server sends the information to it.
##@ Xiao Wuyi
Import socket, sys
Port = 12345
Host = raw_input ('input Server ip Address :')
Data = raw_input ('Enter the message to be sent :')
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Try:
S. connect (host, port ))
Except t:
Print 'Connection error! '
S. send (data)
S. shutdown (1)
Print 'sending completed. '
While 1:
Buf = s. recv (4096)
If not len (buf ):
Break
Sys. stdout. write (buf)

Execution result:

The client inputs hello and the server inputs OK. The displayed result is:

Server:

Connection from: ('127. 0.0.1 ', 127)
127.0.0.1: hello
Input the world: OK
Client:
Input Server ip Address: 127.0.0.1
Enter the message to be sent: hello
Sent successfully.
Hello
I get it!
OK

3. UDP Server

The establishment of a UDP server is similar to that of TCP. The comparison is as follows:

Procedure

UDP

TCP

Step 1

CreateSocketObject

CreateSocketObject

Step 2

SetSocketOption

SetSocketOption

Step 3

Bind to a port

Bind to a port

Step 4

Recvfrom ()

Listen to connect to listen


A time server is created using UDP.

The Code is as follows:

Server side; serverudp. py

Copy codeThe Code is as follows:
#-*-Coding: cp936 -*-
# UDP server, after the client connects, sends the current time to it
##@ Xiao Wuyi
Import socket, traceback, time, struct
Host =''
Port = 12345
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
S. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1)
S. bind (host, port ))

While 1:
Try:
Message, address = s. recvfrom (8192)
Secs = int (time. time ())
Reply = struct. pack ("! I ", secs)
S. sendto (reply, address)
Except T (KeyboardInterrupt, SystemExit ):
Raise
Except t:
Traceback. print_exc ()

Client: clientudp. py

Copy codeThe Code is as follows:
#-*-Coding: cp936 -*-
# Udp client, after sending an empty character to the server, get the server return time
##@ Xiao Wuyi
Import socket, sys, struct, time
Host = raw_input ('input server address :')
Port = 12345
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
S. sendto ('', (host, port ))
Print "waiting for a reply ...... "
Buf = s. recvfrom (2048) [0]
If len (buf )! = 4:
Print "Reply error % d: % s" % (len (buf), buf)
Sys. exit (1)
Secs = struct. unpack ("! I ", buf) [0]
Print time. ctime (int (secs ))

Running result:

Run the server first and then the client.
C: \> python clientudp. py # The clientudp. py program is stored on drive C.
Enter the server address 127.0.0.1.
Wait for a reply ......
Mon Aug 06 17:09:17 2012

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.