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

Network programming socket

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

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

Wedge

You have now learned to write python code. If you write two python files, a.py and b.py, and run them respectively, you will find that the two python files run very well. But if you want to pass a piece of data between these two programs, what do you do?

This problem can be solved with your current knowledge. We can create a file, write what a.py wants to transmit to the file, and then b.py can read from this file.

But what do you do when your a.py and b.py are on different computers?

**

Similar mechanisms include computer network disk, qq and so on. We can chat with others on our computer, and we can upload and download content to the network disk on our own computer. These are two programs communicating.

**

Development architecture

The applications we know that involve communication between two programs can be roughly divided into two types:

The first is the application class: qq, Wechat, Netdisk and Youku are desktop applications that need to be installed.

The second is web: applications such as Baidu, Zhihu, blog Park, etc., which can be directly used by browsers.

The essence of these applications is the communication between two programs. And these two categories correspond to two software development architectures.

Cpact S architecture

Client S and Server, which means client-side and server-side architecture, which is also divided from the user level (or physical level).

The client here generally refers to the client application program EXE, which needs to be installed before it can run on the user's computer, and is highly dependent on the user's computer operating system environment.

2.B/S architecture

Browser S and Server, meaning browser-side and server-side architecture, which is divided from the user level.

Browser browser, in fact, is also a Client client, but this client does not need everyone to install any applications, just request server-side related resources (web resources) through HTTP on the browser, and the client Browser browser can add, delete, modify and query.

Network foundation

Calculator Network Foundation Click the link: https://blog.51cto.com/14068986/2318949

1.socket concept

Understand socket

Socket is the middle software abstraction layer for the communication between the application layer and the TCP/IP protocol family, and it is a group of interfaces. In the design pattern, Socket is actually a facade pattern, which hides the complex TCP/IP protocol family behind the Socket interface. For users, a simple set of interfaces is all, allowing Socket to organize the data to comply with the specified protocol.

Actually, from your point of view, socket is a module. We establish the connection and communication between the two processes by calling the methods already implemented in the module. Some people also refer to socket as ip+port, because ip is used to identify the location of a host on the Internet, and port is used to identify an application on this machine. So as long as we have established ip and port, we can find an application and use the socket module to communicate with it.

two。 The History of socket (socket)

Sockets originated from the 1970s version of Unix at the University of California, Berkeley, known as BSD Unix. As a result, sockets are sometimes called "Berkeley sockets" or "BSD sockets". At first, sockets were designed to communicate between multiple applications on the same host. This is also known as interprocess communication, or IPC. There are two types of sockets (or two races), which are file-based and network-based.

Socket Family based on File Type

Name of the socket family: AF_UNIX

Unix everything is a file. File-based sockets call the underlying file system to fetch data. Two socket processes run on the same machine and can communicate indirectly by accessing the same file system.

Socket Family based on Network Type

Name of the socket family: AF_INET

(AF_INET6 is also used for ipv6, and there are other address families, but they are either used only for a platform or have become obsolete to tcp and udp protocols.

Abandoned, either rarely used or not implemented at all, AF_INET is the most widely used of all address families. Python supports many kinds of address families, but because we only care about network programming, most of the time we only use AF_INET)

3.tcp protocol and udp protocol

TCP:

(Transmission Control Protocol) reliable, connection-oriented protocol (eg: make a call), inefficient full-duplex communication (send cache & receive cache), byte stream oriented. Applications that use TCP: Web browsers; email, file transfer programs.

.

UDP:

(User Datagram Protocol) unreliable, connectionless service, high transmission efficiency (small delay before transmission), one-to-one, one-to-many, many-to-one, message-oriented, best effort service, no congestion control. Applications that use UDP: domain name system (DNS); video streaming; IP voice (VoIP).

I know you don't understand when you say this. Go straight to the picture.

New use of socket (socket)

Socket based on TCP protocol

Tcp is link-based. You must start the server first, and then start the client to link the server.

Server end

Import socketsk = socket.socket () sk.bind (('127.0.0.1)) # bind the address to the socket sk.listen () # listen on the link conn Addr = sk.accept () # accept client link ret = conn.recv (1024) # receive client message print (ret) # print client message conn.send (breadhi') # send message to client conn.close () # close client socket sk.close () # close server socket (optional)

Client end

Import socketsk = socket.socket () # create a customer socket sk.connect (('127.0.0.1 socket 8898)) # try to connect to the server sk.send (baked hellograms') ret = sk.recv (1024) # conversation (send / receive) print (ret) sk.close () # close the customer socket

Problem: some students may encounter when restarting the server

Solution:

# add a socket configuration, reuse ip and port import socketfrom socket import SOL_SOCKET,SO_REUSEADDRsk = socket.socket () sk.setsockopt (SOL_SOCKET,SO_REUSEADDR,1) # that's it Add sk.bind before bind (('127.0.0.1)) # bind the address to the socket sk.listen () # listen on the link conn Addr = sk.accept () # accept client link ret = conn.recv (1024) # receive client message print (ret) # print client message conn.send (breadhi') # send message to client conn.close () # close client socket sk.close () # close server socket (optional)

1. Socket based on UDP protocol

Udp is link-free, and you can accept messages directly after starting the service. There is no need to establish links in advance.

Easy to use

Server end

Import socketudp_sk = socket.socket (type=socket.SOCK_DGRAM) # create a server's socket udp_sk.bind ('127.0.0.1) socket 9000)) # bind server socket msg,addr = udp_sk.recvfrom (1024) print (msg) udp_sk.sendto (baked hi`) Addr) # conversation (receive and send) udp_sk.close () # close the server socket

Client end

Import socketip_port= ('127.0.0.1) udp_sk=socket.socket (type=socket.SOCK_DGRAM) udp_sk.sendto (baked hellographic journal ipmemorport) back_msg,addr=udp_sk.recvfrom (1024) print (back_msg.decode (' utf-8'), addr)

Server

# _ * _ coding:utf-8_*_import socketip_port= ('127.0.0.1) udp_server_sock=socket.socket (socket.AF_INET,socket.SOCK_DGRAM) udp_server_sock.bind (ip_port) while True: qq_msg,addr=udp_server_sock.recvfrom (1024) print (' a message from [% SRAV% s]:\ 033 [1] 44m%s\ 033 [0m'% (addr [0], addr [1], qq_msg.decode ('utf-8')) back_msg=input (' reply message:') .strip () udp_server_sock.sendto (back_msg.encode ('utf-8'), addr)

Client

# _ * _ coding:utf-8_*_import socketBUFSIZE=1024udp_client_socket=socket.socket (socket.AF_INET,socket.SOCK_DGRAM) qq_name_dic= {'Boss Jin': ('127.0.0.1) Boss 8081),' Naju': ('127.0.0.1)),' egg': ('127.0.0.1),' yuan': ('127.0.0.1) } while True: qq_name=input ('Please select someone to chat with:'). Strip () while True: msg=input ('Please enter a message, enter Q to end the chat with him:'). Strip () if msg= = 'q':break if not msg or not qq_name or qq_name not in qq_name_dic:continue udp_client_socket.sendto (msg.encode (' utf-8')) Qq_name_ Dick [QQ _ name]) back_msg,addr=udp_client_socket.recvfrom (BUFSIZE) print ('a message from [% SVR% s]:\ 033 [1] 44m%s\ 033 [0m'% (addr [0], addr [1], back_msg.decode ('utf-8')) udp_client_socket.close ()

Server

# _ * _ coding:utf-8_*_from socket import * from time import strftimeip_port = ('127.0.0.1, 9000) bufsize = 1024tcp_server = socket (AF_INET, SOCK_DGRAM) tcp_server.setsockopt (SOL_SOCKET,SO_REUSEADDR,1) tcp_server.bind (ip_port) while True: msg, addr = tcp_server.recvfrom (bufsize) print (' = = >' Msg) if not msg: time_fmt ='% Y-%m-%d% X' else: time_fmt = msg.decode ('utf-8') back_msg = strftime (time_fmt) tcp_server.sendto (back_msg.encode (' utf-8'), addr) tcp_server.close ()

Client

# _ * _ coding:utf-8_*_from socket import * ip_port= ('127.0.0.1) bufsize=1024tcp_client=socket (AF_INET,SOCK_DGRAM) while True: msg=input (' Please enter a time format (for example% Y% m% d) > >:'. Strip () tcp_client.sendto (msg.encode ('utf-8'), ip_port) data=tcp_client.recv (bufsize)

Detailed explanation of socket parameters

Socket.socket (family=AF_INET,type=SOCK_STREAM,proto=0,fileno=None)

Parameter description for creating a socket object:

Family:

Address series should be AF_INET (default), AF_INET6,AF_UNIX,AF_CAN or AF_RDS.

(the AF_UNIX domain actually uses a local socket file to communicate)

Type:

The socket type should be SOCK_STREAM (default), SOCK_DGRAM,SOCK_RAW, or one of the other SOCK_ constants.

SOCK_STREAM is based on TCP, guaranteed (that is, to ensure the correct transmission of data to the other side) connection-oriented SOCKET, mostly used for data transmission.

SOCK_DGRAM is a UDP-based, non-guaranteed message-oriented socket, which is mostly used to send broadcast messages on the network.

Proto:

The protocol number is usually zero and can be omitted, or if the address family is AF_CAN, the protocol should be one of CAN_RAW or CAN_BCM.

Fileno:

If fileno is specified, other parameters are ignored, causing the socket with the specified file descriptor to return.

Unlike socket.fromfd (), fileno returns the same socket instead of repeating it.

This may help to turn off a separate socket using socket.close ().

The next article is about the sticky bag phenomenon, brothers click on the attention.

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

Network Security

Wechat

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

12
Report