Python Network Programming Learning Notes (III): Socket network server _python

Source: Internet
Author: User
Tags bind current time

1. Method of establishing TCP connection

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

Steps TCP Client TCP Server
First step Create a socket object Create a socket object
Second Step Call Connect () to establish a connection with the server To set the socket option (optional)
Third Step No Bind to a port (or it can be a specified network card)
Fourth Step No Listening for connections

Here's how to build these four steps specifically:

The first step is to create the socket object: here, like the client, it remains:

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

Step two, set and get the socket option

Python defines setsockopt () and getsockopt (), one for setting options and one for getting 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's sol_socket, meaning the SOCKET option you're using. It can also set protocol options by setting a special protocol number, whereas most protocol options are clear for a given operating system, 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 are slightly different depending on the operating system. If level has selected Sol_socket, then 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 it can't be a mobile portable device .

A string that gives the name of the device or an empty string returns 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

Prevent outgoing packets from routers and gateways. This is primarily a method of UDP communication used 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 information packets for TCP traffic continuous. These packets can make it possible for the two sides of the communication to determine that the connection is maintained when no information is transmitted

Boolean-Integer

So_oobinline

You can think of the abnormal data that you receive as normal data, which means that you receive the data 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 some time.

Boolean-Integer



This section in the study, the use of the SO_REUSEADDR option, the specific wording is:

S.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) Here value is set to 1, indicating that the SO_REUSEADDR is marked true, the operating system will release the port of the server immediately after the server socket is closed or the server process terminates, otherwise the operating system will retain the port for several minutes.

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

Copy 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 a server IP, is usually empty, or can be bound to a specific IP address. Port is the port number.

Step Fourth: Listen for connections.

Listens for connections using the Listen () function. The function has only one parameter that indicates how many pending (waiting) connections are allowed to wait in the queue when the server actually handles the connection. As a convention, many people are set to 5. such as: S.listen (5)

2, a 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 received and ' I get it! ' Passed to the client, waiting for a new message to be entered to the client.

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

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

Copy 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 received and the ' I get it! ' Passed to the client, waiting for a new message to be entered to the client.
##@ Small Five Righteousness
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 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 after the exit.
##@ Small Five Righteousness
Import Socket,sys
port=12345
Host=raw_input (' Input server IP: ')
Data=raw_input (' Enter the information 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 results:

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

Server side:

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

3, UDP server

The UDP server is similar to TCP, compared to the following:

Steps

Udp

Tcp

First step

Create a socket object

Create a socket object

Second Step

Set socket options

Set socket options

Third Step

Bind to a port

Bind to a port

Fourth Step

Recvfrom ()

Listening for connections Listen


This uses UDP to establish a time server.

The code is as follows:

Server side; serverudp.py

Copy Code code as follows:

#-*-coding:cp936-*-
# #UDP服务器端, after the client connects, send the current time to it
##@ Small Five Righteousness
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 Code code as follows:

#-*-coding:cp936-*-
# #udp客户端, send a null character to the server, and get the server return time
##@ Small Five Righteousness
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 "Waiting 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))

Run Result:

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