基础版
1、TCP_server端
import socket sk = socket.socket() # 创建了一个socket对象 sk.bind(('127.0.0.1',8080)) # 绑定一台机器的(ip,端口) # 回环地址 - 指向自己这台机器 sk.listen() # 建立监听等待别人连接 conn,addr = sk.accept() # 阻塞:在这里等待直到接到一个连接 # conn是连接 # addr是对方的地址 print(conn) print(addr) conn.send(b'hello') # 和对方打招呼,发送的格式需为byte msg = conn.recv(1024) # 对方和我说的话 # 有发必有收 收发必相等 print(msg) conn.close() # 挂电话 sk.close() # 关机
2、TCP_client端
import socket sk = socket.socket() # 买个手机 sk.connect(('127.0.0.1',8080)) # 拨号 ret = sk.recv(1024) print(ret) sk.send(b'byebye!') sk.close()
聊天小工具
1、server端
import socket sk = socket.socket() sk.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #及时关闭端口,TCP端口复用 sk.bind(('127.0.0.1',9000)) sk.listen() while True: conn,addr = sk.accept() # 接收连接 三次握手conn while True: inp = input('>>>') if inp == 'q': conn.send(inp.encode('utf-8')) break conn.send(inp.encode('utf-8')) msg = conn.recv(1024) if msg == b'q':break print(msg.decode('utf-8')) conn.close() # 四次挥手 sk.close()
2、client端
import socket sk = socket.socket() sk.connect(('127.0.0.1',9000)) while True: msg = sk.recv(1024) print(msg.decode('utf-8')) if msg == b'q':break inp = input('>>>') if inp == 'q': sk.send(inp.encode('utf-8')) break sk.send(inp.encode('utf-8')) sk.close()
3、端口复用举例
import socket tcp1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 在绑定前调用setsockopt让套接字允许地址重用 tcp1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcp2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 接下来两个套接字都也可以绑定到同一个端口上 tcp1.bind(('0.0.0.0', 12345)) tcp2.bind(('0.0.0.0', 12345))
自我练习:
1、客户端
import socket ph = socket.socket() ph.connect(("127.0.0.1",8080)) while 1: info = input(">>>>>>>") ph.send(bytes(info,encoding="utf-8")) res = ph.recv(1024).decode(encoding="utf-8") if res == "关闭": break print(res) ph.close()
2、服务端
import socket ph = socket.socket() ph.bind(("127.0.0.1",8080)) ph.listen() coon,adr = ph.accept() while 1: res = coon.recv(1024).decode(encoding="utf-8") if res == "a": coon.send(bytes("关闭", encoding="utf-8")) break print(res) info = input('>>>>>>') coon.send(bytes(info,encoding="utf-8")) coon.close() ph.close()