Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

10.python Network programming (startin part 1)

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

one。 What is socket?

Socket is created to implement the Cramp S architecture. Socket is located between the application layer and the transport layer. It is a set of interfaces between the transport layer and the application layer. It hides the complex TCP/IP protocol family behind the Socket interface. For users, a simple set of interfaces is all, allowing Socket to organize data to comply with the specified protocol. Therefore, we do not need to have a deep understanding of the tcp/udp protocol. Socket has been packaged for us. We only need to follow the rules of socket to program, and the program naturally follows the tcp/udp standard.

Some people also say that socket is used to identify the location of a host in the Internet, while port is used to identify an application on this machine, the ip address is configured on the network card, and port is opened by the application, and the binding of ip and port identifies a unique application in the Internet.

Add: some people will confuse the socket with the pid of the program, which is the identity of different processes or threads on the same machine.

2. Socket type.

File-based sockets.

AF_UNIX: a file-based socket that fetches data through the underlying file system. Two socket processes run on the same machine, and communication between two programs can be realized by accessing the same file system.

Based on network sockets.

3. Socket workflow.

Tcp server connection establishment process:

Socket () instantiates a socket object → bind () binds the ip address and port → listen () starts listening on the previously bound ip address and port → accept () starts passively receiving the connection from the tcp client and waits for the connection to arrive (if there is no connection, it waits until the client connects.

Tcp client connection establishment process:

The socket () client also initializes a socket object → connect () to actively connect to the server (initialize the connection to the tcp server) if the connection is successful, the client and server can send and receive data to each other. (in fact, connect is equivalent to responding to the accept of the server. The accept of the server has been waiting for the client to connect.)

The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, finally closes the connection, and an interaction ends.

IV. The usage of socket module.

Import socket

Socket.socket (socket_family,socket_type,protocal=0)

Socket_family can be AF_UNIX or AF_INET. Socket_type can be SOCK_STREAM or SOCK_DGRAM. Protocol is generally left empty, and the default value is 0.

Get tcp/ip socket

TcpSock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

Get udp/ip socket

UdpSock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)

Because there are too many attributes in the socket module. We use the 'from module import *' statement as an exception here. With 'from socket import *', we bring all the attributes in the socket module to our namespace, which greatly shortens our code.

For example, tcpSock = socket (AF_INET, SOCK_STREAM)

Proprietary sockets are commonly used on the server:

S.bind (): bind (host, port number) to the socket.

S.listen (): starts tcp snooping. A backlog parameter can be specified in the # listen method, which is used to set the size of the tcp connection pool (the knowledge of tcp connection pool and three-way handshake will be supplemented later. )

S.accept (): passively accept the connection from the TCP customer, (blocking) wait for the connection to arrive.

Proprietary socket methods are commonly used on clients:

S.connect (): initializes the TCP server connection proactively

S.connect_ex (): an extended version of the connect () function that returns an error code instead of throwing an exception when an error occurs.

Common socket methods common to both client and server:

S.recv (): receives tcp data. # you need to specify how many bytes to collect at a time.

S.send (): send tcp data, # send TCP data (when the amount of data to be sent is larger than the remaining space of the peer cache, the data will not be sent out)

S.sendall (): send tcp data, send complete TCP data (in essence, call send,sendall in a loop when the amount of data to be sent is greater than the remaining space of the peer cache, the data will not be lost, and call send until it is finished) (personal analysis, essentially calling the loop)

S.recvfrom (): receives UDP data

S.sendto (): send UDP data

S.getpeername (): the address that connects to the remote end of the current socket

S.getsockname (): address of the current socket

S.getsockopt (): returns the parameters of the specified socket

S.setsockopt (): sets the parameters of the specified socket

S.close (): turn off sockets

5. Examples of socket usage.

Server:

#! / usr/bin/python2.7

#-*-coding:utf-8-*-

Import socket

Address_and_port = ('127.0.0.1)

S1 = socket.socket (family=socket.AF_INET,type=socket.SOCK_STREAM)

S1.bind (address_and_port)

S1.listen (3)

Conn,addr = s1.accept () # after executing the accept method of socket, it begins to block, waiting for the client to connect.

After executing the accept method, a meta-ancestor is returned, which contains a client connection object, as well as the client's ip address and port.

While True:

Data = conn.recv (1024) # is used to receive tcp data, and the following 1024 indicates that recv can receive up to 1024 bytes at a time. (execute to recv, if no data is sent from the peer, or the content is empty, the program will block and not continue to execute downwards. )

Print data

Conn.send (data.upper ())

Conn.close () # closes the connection with the client

S1.close () # closes server socket connection

Client:

#! / usr/bin/python2.7

#-*-coding:utf-8-*-

Import socket

S1 = socket.socket (socket.AF_INET,socket.SOCK_STREAM)

S1.connect (('127.0.0.1))

While True:

Msg = raw_input (">"). Strip ()

S1.send (msg.encode (('utf-8')

Print "client has sent data!"

Data = s1.recv (1024)

Print data

# the above two codes, you can easily understand the workflow of socket.

six。 Solutions to problems such as disconnection of sockt communication client and server collapse (connection loop, communication loop, and exception catch)

Server:

#! / usr/bin/python2.7

#-*-coding:utf-8-*-

Import socket

Address_and_port = ('127.0.0.1)

S1 = socket.socket (family=socket.AF_INET,type=socket.SOCK_STREAM)

S1.bind (address_and_port)

S1.listen (3)

While True: # if you ask about the connection loop here, it will loop and other connections.

Conn,addr = s1.accept () # after executing the accept method of socket, it begins to block, waiting for the client to connect.

After executing the accept method, a meta-ancestor is returned, which contains a client connection object, as well as the client's ip address and port.

While True: # data transfer cycle

Try: # prevent service disruption caused by client disconnection from throwing exceptions.

Data = conn.recv (1024) # is used to receive tcp data, followed by 1024 indicating that recv can receive up to 1024 bytes at a time.

If not data:

Break

Print data

Conn.send (data.upper ())

Except Exception:

Break

Conn.close () # closes the connection with the client

S1.close () # closes server socket connection

Client:

#! / usr/bin/python2.7

#-*-coding:utf-8-*-

Import socket

S1 = socket.socket (socket.AF_INET,socket.SOCK_STREAM)

S1.connect (('127.0.0.1))

While True:

Msg = raw_input (">"). Strip ()

If not msg: # prevent clients from sending empty data

Continue

S1.send (msg.encode (('utf-8')

Print "client has sent data!"

Data = s1.recv (1024)

Print data

S1.close ()

# these are some solutions to prevent the server from crashing.

seven。 About udp sockets.

The operation flow of the server is as follows:

Ss = socket () # create a socket for a server

Ss.bind () # bind server socket

Inf_loop: # Server infinite loop

Cs = ss.recvfrom () / ss.sendto () # conversation (receive and send)

Ss.close () # turn off the server socket

The approximate operation flow of the client:

Cs = socket () # create a customer socket

Comm_loop: # Communication cycle

Cs.sendto () / cs.recvfrom () # conversation (send / receive)

Cs.close () # closes the customer socket

Here is a simple example of a udp socket:

Example 1:

Server:

Import socket

Udp_server = socket.socket (socket.AF_INET,socket.SOCK_DGRAM)

Udp_server.bind (('127.0.0.1))

While True:

Msg,addr = udp_server.recvfrom (1024)

Print msg, addr

Udp_server.sendto (msg.upper (), addr)

Client:

Import socket

Udp_client = socket.socket (socket.AF_INET,socket.SOCK_DGRAM)

While True:

Msg = raw_input ("> >:) .strip ()

If not msg:

Continue

Udp_client.sendto (msg.encode ('utf-8'), ("127.0.0.1", 8888))

Back_msg,addr = udp_client.recvfrom (1024)

Print back_msg.decode ('utf-8'), addr

eight。 What you need to know about tcp sockets and udp sockets.

First of all, there are several points that must be made clear!

Sending and receiving messages are operating their own tcp/udp buffer, sending messages sends data to their own buffer, and receiving messages are also received from the buffer.

1.2 tcp uses send to send messages and recv to receive messages

1.3udp uses sendto to send messages and recvfrom to receive messages

Tcp and udp

2.1 tcp is stream-based and udp is newspaper-based

2.2 when using send to send a data stream, if the data stream is empty, then the tcp buffer (buffer) is also empty, and the operating system will not control tcp to send packets.

Sendinto (bytes_data,ip_port): send Datagram, bytes_data is empty, and ip_port, so even if you send an empty bytes_data, the Datagram is not empty. If the buffer on your side receives the content, the operating system will control the udp protocol to send packets.

3. About the supplement of tcp

Tcp communicates based on links:

Based on links, listen (backlog) is required to specify the size of the semi-connection pool

Based on the link, you must first run the server, and then the client initiates the link request

For mac systems: if one end of the link is broken, the other end of the link will also be finished. Recv will not block and receive empty (solution: the server will add if judgment after receiving the message, and the empty message will break off the communication loop)

For windows/linux systems: if one end of the link is broken, the other end of the link will also be finished. Recv will not block and receive null (the solution is: add exception handling in the server communication loop, and break will drop the communication loop when an exception is caught)

Udp communication.

No links, so no need for listen (backlog), let alone connection pooling

Without links, the sendinto of udp can send messages on its own, regardless of whether there is a running server, but the data is lost.

When the data received by recvfrom is less than that sent by sendinto, the data is lost directly on mac and linux systems, and the direct error message sent on windows system is larger than that received.

Only sendinto sends data without recvfrom receiving data, data is lost.

Note:

1. If you run the above udp client alone, you will find that it will not report an error, on the contrary, tcp will report an error, because the udp protocol is only responsible for sending the packet, and I don't care whether the other party receives it or not, while tcp is based on a link, there must be a server running first, and the client will establish a link with the server and then rely on the link to deliver the message. either party's attempt to destroy the link will lead to the collapse of the other side's program.

two。 In the above udp program, if you comment on any sendinto of the client, the server will get stuck. Why? Because the server has several recvfrom to correspond to several sendinto, even if it is sendinto (baked').

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report