程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Introduction and examples of socket programming in Python

編輯:Python

One Basic knowledge of

Before code implementation , Let's start with a brief introduction TCP,UDP,Socket And so on .

First of all, understand socket( Socket ), We can go through " Socket " Send a request to the network or answer a network request , To enable communication between hosts or processes on a computer .

In addition, in the communication , We use it a lot TCP and UDP,TCP,UDP Connections belonging to the transport layer , The difference between them is TCP It's link oriented , His connection requires three handshakes ; and UDP No connection is established with the other party before data transmission . So generally speaking TCP Than UDP Security , however UDP Than TCP real time .

HTTP Protocols belonging to the application layer , Only the connection transmits data , But without a protocol, we don't know what the transmission is , So we need an application layer HTTP agreement ( Hypertext Transfer Protocol Hypertext Transfer Protocol ).TCP It's the underlying communication protocol , It defines the specification of data transmission and connection mode ;HTTP It's the application layer protocol , What is defined is the specification of the content of the transmitted data ;

We have a connection , You also need an external interface , This is what this article will introduce Socket Socket .Sockert The programming interface is to make it easier for us to use the protocol stack .

Specific introduction can refer to :

TCP and UDP The difference and HTTP agreement

https://segmentfault.com/a/1190000014044351

Socket Connect with HTTP Connect

https://cloud.tencent.com/developer/article/1124905

Two Code example

Let's use python Of Socket Programming , Simple implementation of a client to send requests , After receiving the request, the server returns a json An example of .

The library you need is

import socket

Server code

What the server mainly does

  1. Create socket :socket.socket()
  2. binding IP And port :socket.bind()
  3. Start tcp monitor socket.listen()
  4. Accept tcp Connect , Waiting for data :socket.accept()
  5. receive data :socket.recv()
  6. Send processing data :socket.sendall()
  7. Close socket :socket.close()

among recv and send yes bytes type , So if it's a string or json Format needs to be down converted . Because the project uses json Format , So this article also received str, return json Write examples in the form of .

The detailed code of the server is as follows :

import json
import socket
HOST = '127.0.0.1'
PORT = 8000
ADDR = (HOST,PORT)
def start_server():
# Create socket :AF_INET-- Use ipv4 Address family SOCK_STREAM-- Use streaming sockets
svr_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
svr_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# binding host:port
svr_socket.bind(ADDR)
# setblocking 0-- Non-blocking mode ,1-- Blocking mode The default is 1
svr_socket.setblocking(1)
# Start listening TCP Incoming connections
svr_socket.listen(5)
# Return the new socket and client address
client_socket, addr = svr_socket.accept()
client_socket.settimeout(20.0)
# receive data , Here, the data length is received first ( You need to negotiate the sending format with the client , Whether it is len+data In the form of ), You don't have to do this
data_len = client_socket.recv(4)
length = int.from_bytes(data_len, byteorder="big")
# Specific data received , You can also set a larger buffer here
data = client_socket.recv(length)
print("rev client data", data)
# Data returned to the client , Set to a json
json_msg ={"key":"id","val": 123}
str_msg = json.dumps(json_msg)
# The string should be converted to bytes transmission
client_socket.sendall(str_msg.encode())
# Close socket
client_socket.close()
if __name__ == '__main__':
start_server()

Client code

What the server mainly does

  1. Create socket :socket.socket()
  2. open tcp Connect :socket.connect()
  3. Send request data :socket.sendall()
  4. Receive server data :socket.recv()
  5. Close socket :socket.close()

Complete code :

import json
import socket
HOST = '127.0.0.1'
PORT = 8000
ADDR = (HOST,PORT)
def start_client():
# Create socket
_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# open tcp Connect
_socket.connect(ADDR)
msg = "msg from client"
length = len(msg)
buf = length.to_bytes(4, byteorder="big")
# Send request data len+data Format
_socket.sendall(buf + msg.encode())
# The receiving server returns data
data = _socket.recv(1024)
msg = json.loads(data)
print("client get json", msg)
# Close socket
_socket.close()
if __name__ == '__main__':
start_client()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved