tcp is a link, it must first start the server, and then start the client to the server-based links.
server:
ss = socket () # Creates a server socket ss.bind () # the address bound to the socket ss.listen () # monitor link inf_loop: # server infinite loop cs = ss.accept () # to accept the client links comm_loop: # communication cycle cs.recv () / cs.send () # Dialogue (receive and transmit) cs.close () # close the client socket ss.close () # close the server socket
client:
cs = socket () # Create a client socket cs.connect () # attempt to connect to the server comm_loop: # communication cycle cs.send () / cs.recv () # Dialogue (send / receive) cs.close () # close the client socket
udp is no link, which end will not start before being given
server:
ss = socket () # create a server socket ss.bind () # bind server socket while True: # server infinite loop cs = ss.recvfrom () / ss.sendto () # session (receive and transmit) ss.close () # close the server socket
Client:
cs = socket () # Create a client socket while True: # communication cycle cs.sendto () / cs.recvfrom () # Dialogue (send / receive) cs.close () # close the client socket
UDP instantiated: Server:
import socket ip_port=('127.0.0.1',9000) udp_server_client = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) udp_server_client.bind(ip_port) while True: msg,addr=udp_server_client.recvfrom(1024) print(msg,addr) udp_server_client.sendto (msg.upper (), addr)
the UDP instantiated: Client:
from socket import * udp_cs = socket (AF_INET, SOCK_DGRAM) while True: msg=input('>>: ').strip() if not msg:continue udp_cs.sendto(msg.encode('utf-8'),('127.0.0.1',9000)) msg,addr=udp_cs.recvfrom(1024) print(msg.decode('utf-8'),addr)