2017.07.09 the reuse socket address for Python network programming

Source: Internet
Author: User
Tags echo message socket error

1. Reuse Socket Address:

#-*-Coding:utf-8-*-
# If you run a Python socket server on a port and then terminate the connection once, you cannot use this port.
#!usr/bin/env Python
# Python Network Programming Cookbook--chapter-1
# Optimized for Python 2.7
# It may run on any other version with/without modifications

Import socket
Import Sys

Def reuse_socket_addr ():
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

Old_state=sock.getsockopt (socket. Sol_socket,socket. SO_REUSEADDR)
Print "Old socket status is:%s"%old_state

Sock.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)
New_state=sock.getsockopt (socket. Sol_socket,socket. SO_REUSEADDR)
Print "New socket status is:%s"%new_state

local_port=8282

Srv=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Srv.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)
Srv.bind ((' ', Local_port) ')
Srv.listen (1)
Print "Listening port yes:%s"%local_port

While True:
Try
Connection,addr=srv.accept ()
Print "Connection is%s"% (Addr[0],addr[1])
Except Keyboardinterrupt:
Break
Except socket.error,msg:
print '%s '% (MSG,)


If __name__== ' __main__ ':
REUSE_SOCKET_ADDR ()

2. Obtain and print the current time from the network time server:

#-*-Coding:utf-8-*-
# Many programs require the device to be time-accurate, the time on the device may not be accurate, and the time servers in the network need to be synchronized
# Write a Python client to synchronize the time on the device with a network server, to complete this step, use Ntplib,
# Through Network Time protocol, NTP handles communication between client and server, pip install Ntplib
#!usr/bin/env Python
# Python Network Programming Cookbook--chapter-1
# Optimized for Python 2.7
# It may run on any other version with/without modifications

Import Ntplib
From time import CTime

Def print_time ():
Ntp_client=ntplib. NTPClient ()
Response=ntp_client.request (' cn.pool.ntp.org ')
Print CTime (response.tx_time)

If __name__== ' __main__ ':
Print_time ()

3. Write a SNTP client (Simple Network Time Protocol):

#-*-Coding:utf-8-*-
# Sometimes there is no need to get accurate time from the NTP server, you can use the simplified version of NTP, Simple Network Time Protocol
#!usr/bin/env Python
# Python Network Programming Cookbook--chapter-1
# Optimized for Python 2.7
# It may run on any other version with/without modifications

Import socket
Import struct
Import Sys
Import time

Ntp_server= "0.cn.pool.ntp.org"
time1970=2208988800l

Def sntp_client ():
Client=socket.socket (Socket.af_inet,socket. SOCK_DGRAM)
Data= ' \x1b ' +47* '
Client.sendto (data, (ntp_server,123))
Data,address=client.recvfrom (1024)

If data:
print ' Receive data from: ', address
T=struct.unpack ('!12i ', data) [10]
t-=time1970
print ' \ t time is:%s '%time.ctime (t)

If __name__== ' __main__ ':
Sntp_client ()


4. Write a simple echo client/server application:

Server program:

#-*-Coding:utf-8-*-
# In this case, whatever input the server receives from the client will be shown back,
# using the Argparse module in Python, specify the TCP port server script and client script on the command line to use this parameter
#!usr/bin/env Python
# Python Network Programming Cookbook--chapter-1
# Optimized for Python 2.7
# It may run on any other version with/without modifications

Import socket
Import Sys
Import Argparse

host= ' localhost '
data_payload=2048
Backlog=5


def echo_server (Port):
"" A simple Echo server app "" "
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

Sock.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)
Server_address= (Host,port)
Print "Starting up Echo server on%s port%s"%server_address

Sock.bind (server_address)
Sock.listen (Backlog)
Port=int (Port)
While True:
Print "Waiting to receive information from client"
Client,address=sock.accept ()
DATA=CLIENT.RECV (Data_payload)
If data:
print "data:%s"%data
print "Send%s bytes back to%s"% (data,address)
client.send (data)
Client.close ()

If __name__== ' __main__ ':
Parser=argparse. Argumentparser (description= ' Socket Server Example ')
Parser.add_argument ('--port ', action= "store", dest= "Port", Type=int,required=true)
Given_args=parser.parse_args ()
Port=given_args.port

Echo_server (Port)


Client program:

#-*-Coding:utf-8-*-
# In this case, whatever input the server receives from the client will be shown back,
# using the Argparse module in Python, specify the TCP port server script and client script on the command line to use this parameter
#!usr/bin/env Python
# Python Network Programming Cookbook--chapter-1
# Optimized for Python 2.7
# It may run on any other version with/without modifications

Import socket
Import Sys

Import Argparse

host= ' localhost '

def echo_client (Port):
"" "A simple echo message for the client" ""
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Server_address= (Host,port)

Print "Port%s connected to server%s"%server_address
Sock.connect (server_address)

Try
message= "Test message. This is would be echoed "
Print "Send message%s"% message
Sock.sendall (Message)


amount_received = 0
amount_excepeted = len (message)
While amount_received < amount_excepeted:

DATA=SOCK.RECV (1024)

Print len (data)

Amount_received+=len (data)
Print amount_received
Print "Received data:%s"% data

Except Socket.errno,e:
Print "Socket error:%s"%str (e)

Except Exception,e:
Print "Other exception:%s"%str (e)

Finally
Print "Closeing Connection to the server"
Sock.close ()



If __name__== ' __main__ ':
Parser=argparse. Argumentparser (description= ' socket Service case ')
Parser.add_argument ('--port ', action= "store", dest= "Port", Type=int,required=true)
Given_args=parser.parse_args ()
Port=given_args.port
Echo_client (Port)

A detailed explanation of the python socket:

The socket is divided into two types: blocking and non-blocking, which can be set by setsockopt, or simpler setblocking, settimeout.  The recv of a blocked socket obeys the rule that all data is returned immediately when there is data in the buffer, and when there is no data in the buffer, it is blocked until there is data in the buffer. The recv of a non-blocking socket is that when there is data in the buffer, all data is returned immediately, and when there is no data in the buffer, a eagain error is generated and returned (an exception is thrown in Python).   Neither case returns an empty string, and the result of returning empty data is that the other person closes the connection before it appears. Since the TCP socket is a stream, there is no "read the data sent by the other" thing. You have to judge whether the next recv will be done after each reading of the data, judging by the data itself to see if the data that is currently waiting is all received. There is a blog post written very well, accidental discovery, recommended to the people who are learning: http://blog.csdn.net/rebelqsp/article/details/22109925

2017.07.09 the reuse socket address for Python network programming

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.