基于TCP:

import socket sk = socket.socket() sk.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # 有了这段代码就可重复使用端口了。 sk.bind(('127.0.0.1',9000)) sk.listen() # 可以加参数,表示同一个时间可以有n个链接等待与server端通信 while True: conn,addr = sk.accept() # 接收 连接的客户端的连接 while True: ret = conn.recv(1024).decode('utf-8') # 将接受的内容解码 if ret.upper() == 'Q':break print(ret) inp = input('>>>') conn.send(inp.encode('utf-8')) if inp.upper() == 'Q':break conn.close() sk.close()

import socket sk = socket.socket() sk.connect(('127.0.0.1',9000)) while True: inp = input('>>>') sk.send(inp.encode('utf-8')) if inp.upper() == 'Q': break ret = sk.recv(1024).decode('utf-8') if ret.upper() == 'Q':break print(ret) sk.close()
基于UDP:

import socket sk = socket.socket(type=socket.SOCK_DGRAM) sk.bind(('127.0.0.1',9000)) while True: msg,addr = sk.recvfrom(1024) print(msg.decode('utf-8')) inp = input('>>>') sk.sendto(inp.encode('utf-8'),addr) sk.close()

import socket sk = socket.socket(type=socket.SOCK_DGRAM) while True: inp = input('>>>') if inp.upper() == 'Q':break sk.sendto(inp.encode('utf-8'),('127.0.0.1',9000)) msg,addr = sk.recvfrom(1024) print(msg.decode('utf-8')) sk.close()
进阶(加上客户端的名称以及上色):

import socket lst = {'顾清秋':'