Python full-time eight Day31 2019/5/28

socket

1. What is the socket: Socket software application is the intermediate layer and the TCP / IP protocol suite to communicate abstraction layer, which is a set of interfaces that the complex TCP / IP protocol suite Socket hidden behind the interface. In short he is a module, the interface contains the communication protocol.

2. Use the socket purpose: With socket later, without having to write your own code to achieve three-way handshake, four waving, ARP request, packed data, etc., socket has a good package, just need to follow the provisions of the socket to program, write program is to follow the natural tcp / udp standards. (Time and cost savings to improve development efficiency)

3. Note: to be clear: the network protocols on relevant concepts and socket, for all programming languages are the same, just with different names for each programming language function

python in the socket

# Import socket module 1. 
Import socket

# 2. Create a socket object function is defined as follows
socket.socket (socket_family, socket_type, Protocal = 0)
# socket_family may be AF_UNIX or AF_INET.
# Socket_type can be SOCK_STREAM SOCK_DGRAM the TCP protocol or the UDP protocol.
# Protocol generally does not fill, the default value is 0.

# 2.1 get a TCP socket
tcpSock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
# or the back of the parameters have default values, you can not write, created by default protocol is TCP socket
tcpSock socket.socket = ()

# 2.2 Get udp / ip socket
udpSock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)

# socket module since there are too many attributes. You can use 'from module import *' statements. Use 'from socket import *', the inside of the socket module all attributes into the current namespace, and this can dramatically shorten the code.
# For example: tcpSock = socket (AF_INET, SOCK_STREAM )
To be clear: Whether the client server-side use of socket objects are
concrete examples:
Client:
Socket Import 

Client socket.socket = ()
# ip and port specified server client system automatically assigns the port side of
the client.connect (( "127.0.0.1", 8989)) #


# add cyclic data transceiver to repeat
the while True:
# send and receive very opposite of the order must be opposite or card dead
msg = input ( "Please enter your details: (q: quit)")
IF msg == "q": BREAK
IF not msg: the Continue
client.send (msg.encode ( "UTF -8 "))
! Print (" sended ")
Data = client.recv (1024)
Print (data.decode (" UTF-. 8 "))

client.close ()
server:
Import socket 

# as the server must clear their ip and port numbers and should not change
# 1 specifies the socket type AF_INET parameter indicates the type of network
# 2 specified by the transport protocol parameter is the TCP protocol SOCK_STREAM SOCK_DGRAM UDP protocol
server = socket.socket (socket. AF_INET, socket.SOCK_STREAM) # 1. buy a phone

# is the default type of network protocol TCP
#server socket.socket = ()

# this is called the loopback address 127.0.0.1 indicates that the current computer itself
# ip local ip certain the unit may have multiple IP (wireless | limited)
# Note: need argument is a tuple port is an ordinary integer
server.bind (( "127.0.0.1", 1688 )) # 2. card inserted into the phone

# either server-side or client is the type of socket

# 1688 starts listening to port after port stared at the data to see not come
server.listen () # 3. start standby phone

# to receive a link request
# the first is a client of the second client socket address information
client, addr = server.accept () # 4. phone
# Print (type (Client))
# Print (addr)


# 5. The data transceiver
data = client.recv(1024)
print(data)
client.send("copy!".encode("utf-8"))

server.close() # 关机

TCP communication process

 

 The focus is first to accept the call request to establish a call connection, TCP attention must first start the server and then start the client, or the client because the server can not be linked directly to an error!

Note: in order to establish the transmission data, the transmission data two one-time transmission is not a lot of time to complete, the process requires multiple transceivers, it is necessary to code with the following cycle

Client:

Socket Import 

Client socket.socket = ()
# ip and port specified server client system automatically assigns the port side of
the client.connect (( "127.0.0.1", 8989)) #


# add cyclic data transceiver to repeat
the while True:
# send and receive very opposite of the order must be opposite or card dead
msg = input ( "Please enter your details:")
IF not msg: the Continue
client.send (msg.encode ( "UTF-8"))
( "! sended") Print
the Data = client.recv (1024)
Print (data.decode ( "UTF-. 8"))


client.close ()
server
socket Import 
Server = socket.socket ()
server.bind (( "127.0.0.1", 8989))
server.listen ()

the while True:
client_socket, client_addr = server.accept ()
buffer_size = 1024 # buffer is a temporary container  
# can not just write buffer size too large too small to cause a memory overflow low efficiency in the case of larger memory can withstand

the while True:
the try:
the Data = client_socket.recv (1024)
# in linux each other if they were forced off the assembly line server no exception is thrown only receive a blank message
# get together to determine if it means that the other side is down empty should close links out of the loop
on # windows normal shutdown will also receive an empty message if needed to be added
if not data:
client_socket.close ()
BREAK

Print (data.decode ( "UTF-8")) # make sure both sides agree encoding decoding
# hair back in uppercase
client_socket.send (data.upper ())
the except ConnectionResetError AS E:
Print ( "% S% S"% (client_addr [0], client_addr [. 1]), E)
# server if the other side is down and that it should close the corresponding the client object
client_socket.close ()
BREAK


# usually the server does not close the
# server.close ()

Common Errors

1. Port occupation

# If you have turned on the server running again occupied the port will throw an exception to open before you can turn off the server 
"" "
In some cases obviously has shut down the process but still occupies port
may be a process running in the background can be found through port progress to shut down
under Windows
netstat -ano | findstr 9898
tasklist | findstr process id to get the process name
taskkill / f / t / im process name

big move: restart the computer

2. forced to close links

1. When the customer end and server link is successful, if the party does not perform close, but directly forcibly terminate the program (or an exception is encountered forced termination), it will lead to other problems sent, in windows, the party receiving data recv function will throw an exception at

2. Error display:

ConnectionResetError: [WinError 10054] forcibly closed by the remote host an existing connection.

3. Note:

Under linux, no exception is thrown will lead the party receiving data, recv methods continue to receive an empty message, resulting in an infinite loop

For applications to different platforms to work properly, it needs to deal with the two issues separately

4. Solution:

Client

Socket Import 

Client socket.socket = ()
# ip and port specified server client system automatically assigns the port side of
the client.connect (( "127.0.0.1", 8989)) #


# add cyclic data transceiver to repeat
the while True:
# send and receive very opposite of the order must be opposite or card dead
msg = input ( "Please enter your details: (q: quit)")
IF msg == "q": BREAK
IF not msg: the Continue
client.send (msg.encode ( "UTF -8 "))
Print (" sended! ")
Data = client.recv (1024)
Print (data.decode (" UTF-. 8 "))

client.close ()

 server

socket Import 
Server = socket.socket ()
server.bind (( "127.0.0.1", 8989))
server.listen ()

the while True:
client_socket, client_addr = server.accept ()
buffer_size = 1024 # buffer is a temporary container  
# can not just write buffer size too large too small to cause a memory overflow low efficiency in the case of larger memory can withstand

the while True:
the try:
the Data = client_socket.recv (1024)
# in linux each other if they were forced off the assembly line server no exception is thrown only receive a blank message
# get together to determine if it means that the other side is down should close links out of the loop is empty
IF not the data:
client_socket.close ()
BREAK

Print ( "receive data:" data.decode ( "utf-8") ) # make sure both sides agree encoding decoding
# hair back in uppercase
client_socket.send (data.upper ())
the except AS Error E:
Print ( "% S% S"% (client_addr [0], client_addr [. 1]), E)
# server if the other side is down and that should close the corresponding the client object
client_socket.close ()
BREAK


# usually the server does not close the
# server.close ()

 

Guess you like

Origin www.cnblogs.com/tfzz/p/10939672.html