python - socket programming

Socket is the application layer and the intermediate software TCP / IP protocol suite to communicate abstraction layer, which is a set of interfaces. In design mode, Socket is actually a facade pattern, it is the complexity of TCP / IP protocol suite 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.

So, 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.

 

# - simple example is based on TCP / IP socket server-side

# Tcp is based link, you must first start the server, and then start the client to the server links

Server initialized Socket, then the port binding (bind), listens to port (listen), call accept blocks, 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

from socket import socket
ip_port=("127.0.0.1",8080)
buf_size=1024

tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(5)
conn,addr=tcp_server.accpet()
msg=conn.recv(buf_size)
print("收到客户端发送的消息",msg.decode("utf-8"))
conn.send(msg.upper())
conn.close()
tcp_server.close()
tcp_server server

# Simple example is based on TCP / IP socket client

from socket import *
ip_port=("127.0.0.1",8080)
buf_size=1024
tcp_client=socket(AF_INET,SOCK_STRAM)
tcp_client.connect(ip_port)
tcp_client.send("hello".encode("utf-8"))
data=client.recv(buf_size)
print("客户端收到消息",data.decode("utf-8"))
tcp.client.close()
tcp_client client

 

# Socket server based on the example of UDP

# Udp is no link, which end will not be started error

from socket import *
ip_port=("127.0.0.1",8080)
buf_size=1024
udp_server=socket(AF_INET,SOCK_DGRAM)
udp_server.bind(ip_port)
msg,addr=udp_server.recvfrom(buf_size)
print("服务端收到消息",msg.decode("utf-8"))
udp_server.sendto(msg.upper(),addr)
udp_server server

# UDP socket-based client-side example of

from socket import *
ip_port=("127.0.0.1",8080)
buf_size=1024
udp_client=socket(AF_INET,SOCK_DRGAM)
udp_client.sendto("hello".encode("utf-8"),ip_port)
data,addr=udp_client.recvfrom(bufsize)
print(data.decode("utf-8"))
udp_client client

 

Guess you like

Origin www.cnblogs.com/tangcode/p/11534052.html