Python Network Programming Learning Note (III): Socket network server

Source: Internet
Author: User
1, the establishment of TCP connection method

The client typically takes two steps to establish a TCP connection, and the server process takes four steps, as shown in the following comparison.

Steps TCP Client TCP Server
The first step Set up a socket Object Establish Socket Object
Step Two Call Connect () to establish a connection to the server Set Socket options (optional)
Step Three No Bind to a port (can also be a specified NIC)
Fourth Step No Listening for connections

Here's how these four steps are built:

The first step is to set up the socket object: here, as with the client, remains:

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

Step two, set and get socket options

Python defines setsockopt () and getsockopt (), one is the setup option and the other is set. Here the main use of setsockopt (), the specific structure is as follows:

SetSockOpt (Level,optname,value)

Level defines which option will be used. Usually it is sol_socket, which means the SOCKET option is being used. It can also set protocol options by setting a special protocol number, but for a given operating system, most protocol options are clear, so for simplicity, they are rarely used for applications designed for mobile devices.

The optname parameter provides special options for use. The settings for the available options vary slightly depending on the operating system. If level Sol_socket is selected, some common options are shown in the following table:

Options

Significance

Expectations

So_bindtodevice

You can make the socket valid only on a particular network interface (NIC). Maybe not a mobile portable device .

A string gives the name of the device or an empty string to return the default value

So_broadcast

Allow broadcast addresses to send and receive packets. Valid only for UDP . How to send and receive broadcast packets

Boolean integer

So_dontroute

Sending packets out through routers and gateways is prohibited. This is primarily a way to use UDP traffic on Ethernet for security purposes . prevents data from leaving the local network, regardless of the IP address used for the destination address

Boolean integer

So_keepalive

You can keep packets of TCP traffic contiguous. These packets can make sure that the connection is maintained when no information is transmitted .

Boolean integer

So_oobinline

The abnormal data received can be considered as normal data, which means that the data will be received through a standard call to recv () .

Boolean integer

So_reuseaddr

When the socket is closed, the port number that the local side uses for the socket can be reused immediately. In general, it can be reused only after the system has been defined for a period of time.

Boolean integer



In this section, we use the SO_REUSEADDR option when studying, specifically:

S.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) Here value is set to 1, which means that the SO_REUSEADDR is marked as true, and the operating system releases the port of the server immediately after the server socket is closed or the server process terminates, otherwise the operating system retains the port for a few minutes.

The following methods can help give a list of socket options supported by Python under this system:

Copy the Code code as follows:


Import socket
Solist=[x for x in DIR (socket) if X.startswith (' So_ ')]
Solist.sort ()
For x in Solist:
Print x

Step three: Bind the socket

Binding requires a port number for the server.

S.bind ((Host,port)), where host is the server IP, usually empty, or can be bound to a specific IP address. Port is the port number.

Fourth step: Listen for connections.

Use the Listen () function to listen for connections. The function has only one parameter, which indicates how many pending (waiting) connections are allowed to wait in the queue when the server actually processes the connection. As a convention, many people are set to 5. Example: S.listen (5)

2. Simple TCP Server Instance

This builds a simple TCP server and client.

Server-side: TCP Response Server, when a connection is established with the client, the server displays the client IP and port while the client information is received and ' I get it! ' To the client, waiting for the input of a new message to be passed to the client.

Client: TCP Client, enter the server IP address first, then enter the information, return to the server will be returned information, and then wait for the server to send information to exit.

The specific code is as follows:
Server side: tcpserver.py

Copy the Code code as follows:


#-*-coding:cp936-*-
# #tcp响应服务器, when a connection is established with the client, the server displays the client IP and port while the client information is received and ' I get it! ' To the client, waiting for the input of a new message to be passed to the client.
##@ Xiao Wu Yi
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 Keyboardinterrupt:
Raise
Except
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 (Keyboardinterrupt,systemexit):
Raise
Except
Traceback.print_exc ()

Try
Clientsock.close ()
Except Keyboardinterrupt:
Raise
Except
Traceback.print_exc ()

Client: tcpclient.py

Copy the Code code as follows:


#-*-coding:cp936-*-
# #tcp客户端, first enter the server IP address, and then enter the information, return to the server will be returned information, and then wait for the server to send information to exit.
##@ Xiao Wu Yi
Import Socket,sys
port=12345
Host=raw_input (' Input server IP: ')
Data=raw_input (' Enter the message to send: ')
S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Try
S.connect ((Host,port))
Except
print ' connection Error! '
S.send (data)
S.shutdown (1)
print ' send complete. '
While 1:
BUF=S.RECV (4096)
If not Len (BUF):
Break
Sys.stdout.write (BUF)

Execution Result:

Client input Hello, server-side input OK, the results are as follows:

Server-side:

Connection from: (' 127.0.0.1 ', 1945)
127.0.0.1:hello
Input the World:ok
Client:
Input server ip:127.0.0.1
Enter the message you want to send: Hello
Send complete.
Hello
I Get it!
Ok

3. UDP server

The UDP server is established similar to TCP, with the following specific comparisons:

Steps

Udp

Tcp

The first step

Set up a socket Object

Set up a socket Object

Step Two

Set socket Options

Set socket Options

Step Three

Bind to a port

Bind to a port

Fourth Step

Recvfrom ()

Listening for connection Listen


Here, UDP is used to establish a time server.

The code is as follows:

Server side; serverudp.py

Copy the Code code as follows:


#-*-coding:cp936-*-
# #UDP服务器端, after the client connects, send the current time to it
##@ Xiao Wu Yi
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 (Keyboardinterrupt,systemexit):
Raise
Except
Traceback.print_exc ()

Client: clientudp.py

Copy the Code code as follows:


#-*-coding:cp936-*-
# #udp客户端, after sending a null character to the server, get the server return time
##@ Xiao Wu Yi
Import Socket,sys,struct,time
Host=raw_input (' Enter server address: ')
port=12345
S=socket.socket (Socket.af_inet,socket. SOCK_DGRAM)
S.sendto (", (Host,port))
print "Wait for 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))

Operation Result:

Run the server side first, and then run the client.
C:\>python clientudp.py # #clientudp. py program stored under C drive
Enter server address: 127.0.0.1
Waiting for a reply ...
Mon 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.