Using socket programming can be divided into TCP-based and based on UDP,TCP and UDP The main difference is whether there is a connection-oriented.
TCP -based socket process:
UDP -based socket flowchart:
(The above two figures are from the network)
You can see that UDP-based sockets are much simpler, UDP clients do not need to connect in advance, and UDP servers do not need listen and accept.
The following is a simple implementation code labeled TCP Client, TCP server, UDP client, UDP server
TCP Client:
__author__ = " seven " import Sockettarget_host = 127.0.0.1 " target_port = 80client = Socket.socket (socket.af_inet, socket. Sock_stream) Client.connect ((Target_host, Target_port)) client.send ( abcdef " = CLIENT.RECV (4096) print Response
Client.close ()
TCP Server:
__author__='Seven'ImportSocketImportthreadingbind_ip="0.0.0.0"Bind_port= 80Server=Socket.socket (socket.af_inet, socket. Sock_stream) Server.bind ((Bind_ip, Bind_port)) Server.listen (5)Print "[*] Listening on%s:%d"%(BIND_IP, Bind_port)defhandle_client (client_socket): Request= CLIENT_SOCKET.RECV (1024) Print "[*] Received:%s"%Request Client_socket.send ("ack!") Client_socket.close () whiletrue:client, addr=server.accept ()Print "[*] Accepted connection from:%s:%d"% (Addr[0], addr[1]) Client_handler= Threading. Thread (Target=handle_client, args=(client,)) Client_handler.start ()
Server.close ()
UDP client:
__author__ ' Seven ' Import "127.0.0.1"= socket.socket (socket.af_inet, Socket. SOCK_DGRAM) client.sendto ("ABCDEF"= client.recvfrom (4096) Print data
Client.close ()
UDP server:
__author__='Seven'Importsocketbind_ip="0.0.0.0"Bind_port= 80Server=Socket.socket (socket.af_inet, socket. SOCK_DGRAM) Server.bind ((Bind_ip, bind_port)) whileTrue:data, addr= Server.recvfrom (4096) if notData:Print "client has exist" BreakServer.sendto ("ack!", addr)Print "received:%s from%s"%(data, addr) server.close ()
Explain some of the parameters a little bit:
Af_inet parameter description using a standard IPV4 address or host name
Af_inet6 parameter description use IPV6 address or host name
The Sock_stream parameter description is a TCP client
The Sock_dgram parameter description is a UDP client
Network programming using the Python socket module