Python network programming study notes (III): socket network server

Source: Internet
Author: User
The server is very similar to the client program. The client program is learned in the previous section. This section describes how to use socket to establish TCP and UDP servers. 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:

The 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

The 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

The 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

The 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

The 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

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.