socket socket programming

SOCKET

First, based on socket socket programming TCP protocol

1.1 What is a socket

is a socket abstraction layer between the application layer and the transport layer, we often called a socket socket, which is a set of interfaces, the complicated operation abstract TCP / IP layer is supplied with a few simple interface layer calls to implement interprocess communication in the network.

In design mode, socket is actually a facade pattern, it is the complexity of TCP / IP protocol hidden behind the socket interface, for users, a simple interface is all set, let socket to organize data in order to comply with the specified protocol. We do not need in-depth understanding of tcp / udp protocol, socket has a good package for us, we just need to follow the provisions of the socket to program, write a program that follows the natural tcp / udp standards.

1.2 Socket classification

  • AF_UNIX, only two sockets processes running on the same machine, and now this basic need: file type socket-based family
  • Based on the type of network sockets family: AF_INET, which is one of the most widely used, can be used on different machines

1.3 socket workflow

Start talking about the server, the server first initialize socket, then the port binding (bind), listens to port (listen), accept blocked calls, waiting for client connections. At this point if you have a client initiates a socket, then connect to the server (connect), if the connection is successful, then connect the client and the server is established. The client sends a data request, the server receives the request and processes the request, and then sends the response data to the client, the client reads the data, and finally close the connection, ends of an interaction. Example The following code is used directly:

  • Based on the simple protocol of TCP socket programming
# 简单的tcp通信服务端
# 以买手机打电话举例,socket.SOCK_STREAM表示建立tcp连接,socket.SOCK_DGRAM表示建立udp连接
# 导入socket模块
import socket
# 实例化一个socket对象(买了个手机)
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定ip地址(插电话卡),参数传元组:(ip,端口号)
# soc.bind(('127.0.0.1',8080))  # ip写127.0.0.1,只能自己访问
soc.bind(('192.168.11.176',8080))  # 如果写本机ip,局域网外部可以访问
# 监听(手机开机),这个5是半连接池的大小
soc.listen(5)
# 等待客户端连接(等待别人给我打电话)
print('start>>>')
conn,addr = soc.accept()   # conn:通路(三次握手建立的双向连接),addr:(客户端的ip,端口)
# 通信:收/发消息
data = conn.recv(1024)  # 一次最大接收1024字节数
print('来自客户端的数据>>>',data)
# 发送数据,数据必须是bytes格式
conn.send(data.upper())  # 把接收到的客户端的数据变成大写发送回去
# 关闭通路(挂断电话)
conn.close()
# 关闭连接(销毁手机)
soc.close()
# 简单的tcp通信客户端

import socket
# 创建一个socket对象
soc = socket.socket()  # 不传参默认是tcp协议
# 连接服务端
soc.connect(('192.168.11.176',8005))  # 指定服务端ip和端口
# 通信:发/收消息
soc.send(b'zyl')  # 发送数据,必须是bytes格式,也可以用soc.send('zyl'.encode('utf8'))
data = soc.recv(1024)  # 接收数据
print('收到服务端的数据>>>',data)
# 关闭连接
soc.close()
  • Add connection and communication based on the TCP socket programming cycle protocol
# 服务端

import socket
# 生成一个socket对象
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定地址和端口号
soc.bind(('127.0.0.1',8005))  # 127.0.0.1只能自己访问
# 监听(半连接池的大小,不是连接数)
soc.listen(5)
# 等待客户端连接
while True:  # 连接循环
    print('等待客户端连接')
    conn,addr = soc.accept()  # 卡住,如果没有客户端连接,会一直卡在这,当有客户端连接,才继续往下走
    print('有个客户端连接上了',addr)
    while True:  # 通信循环
        try:
            # windows如果客户端断开,会报错,所以加了try
            # linux如果客户端断开,不会报错,会收到空,所以当data为空时,也break
            # 等待接收,最大收取1024个字节
            data = conn.recv(1024)   # 会卡住,当客户端有数据过来,才会执行
            if len(data) == 0: # 处理linux客户端断开,在window下这段代码根本不会执行(即便是客服端发了空,也不会走到这行代码)
                break
            print(data)
            conn.send(data.upper())
        except Exception:
            break
    # 关闭通路
    conn.close()
# 关闭连接
soc.close()
# 客户端

import socket
# 创建一个socket对象
soc = socket.socket()
soc.connect(('127.0.0.1',8005))

while True:  # 通信循环
    in_s = input('请输入要发送的数据>>>').strip()
    # 发送的数据必须是b格式,in_s.encode('utf-8')  把字符串编码成b格式
    # 把b格式转成字符串
    # ss=str(b'hello',encoding='utf-8')
    # ss=b'hello'.decode('utf-8')
    # #把字符串转成b格式
    # by=bytes('hello',encoding='utf-8')
    # by='hello'.encode('utf-8')
    soc.send(in_s.encode('utf8'))  # 发送数据给服务端
    data = soc.recv(1024)   # 接收服务端发送的数据
    print('收到服务端数据>>>',data)

# 关闭连接
soc.close()

Second, based on udp socket programming agreement

Here it is written directly after adding the communication cycle service and client, because udp protocol does not require a connection

# 服务端
import socket
server = socket.socket(type=socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8005))
while True:  # 通信循环
    data,addr = server.recvfrom(1024)  # udp协议无需等待连接和监听
    print(data)
    server.sendto(data.upper(),addr)  # 返回处理好的数据给客户端
    
# 客户端
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
while True:  # 通信循环
    msg = input('请输入要发送的数据>>>').strip()
    # 直接发送数据
    client.sendto(msg.encode('utf8'),('127.0.0.1',8005))  # 发送bytes格式的数据和地址
    # 接收数据
    data = client.recvfrom(1024)
    print(data)

Three differences, UDP protocol and TCP protocol

Features 3.1 udp protocol

  • Without establishing a connection, do not need to listen, you can send data directly, without receipt, the client and server ports will not affect who sent it just sent, it is not reliable
  • Empty the contents can be sent, no problem stick package, but will packet loss, regardless of whether the client or the server is received, it is just hair, it is not reliable

The difference between 3.2 UDP and TCP

TCP UDP
Reliable connection Unreliable connection
Based on the transmission data stream Transmit data packets based
Stick package Non-stick package
Packet loss Loss

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11503344.html