import socket sk = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM,) 参数1 family: 套接字类型 参数2 type : 通信协议类型 tcp协议,udp协议 tcp协议:SOCK_STREAM udp协议:SOCK_DGRAM family=socket.AF_INET 采用网络形式通信的套接字 family=socket.AF_UNIX 采用文件类型通信的套接字
TCP一人聊天:
服务器:
import socket sk = socket.socket(type = socket.SOCK_STREAM) # 采用tcp协议 买了个新手机 sk.bind(('192.168.19.200',9090)) # 端口号范围:0-65535 0 - 1023(不能用) 8000 - 10000 (常用) 买一个手机卡 sk.listen() # 告诉好友我的新手机号 print(123) conn,addr = sk.accept() # 等待好友来给我打电话 #(三次握手) print(456) msg = conn.recv(1024) # 聊天 (recv接收消息) print(msg.decode('utf-8'),addr,conn) conn.send(b'hahaha') (send发送消息) conn.close() # 挂掉电话 sk.close() # 关机 #(四次挥手在两个close之间)
客户端;
import socket sk = socket.socket() sk.connect(('127.0.0.1',9200)) sk.send(b'hello') sk.close()
TCP多人聊天:
服务器:
import socket sk = socket.socket(type=socket.SOCK_STREAM) sk.bind(('127.0.0.1',9090)) sk.listen() while 1: #(接收多个连接针对 conn,addr = sk.accept()) # print(123) conn,addr = sk.accept() # 等待连接 -- 阻塞 # print(456) while 1: # (接收多个消息) # print(789) msg_r = conn.recv(1024).decode('utf-8') # 阻塞等待接收客户端发来的消息 # print('jqk') print('接收到来自%s的一个消息:%s' % (addr, msg_r)) if msg_r == 'q': break msg_s = input('>>>') conn.send(msg_s.encode('utf-8')) # 发送给客户端消息 if msg_s == 'q': break conn.close()# 服务器和当前客户端断开连接,程序回到上一层死循环,重新等待客户端的连接 sk.close()
客户端:
import socket sk = socket.socket() sk.connect(('127.0.0.1',9090)) while 1: msg_s = input('>>>') sk.send(msg_s.encode('utf-8')) if msg_s == 'q': break msg_r = sk.recv(1024).decode('utf-8') print(msg_r) if msg_r == 'q': break sk.close()
UDP:一人聊天:
服务器:
import socket sk = socket.socket(type=socket.SOCK_DGRAM) # udp协议 sk.bind(('127.0.0.1',9040)) msg_r,addr = sk.recvfrom(1024) #接收来自哪里的消息 print(msg_r) sk.sendto(b'oo',addr) sk.close()
客户端:
import socket sk = socket.socket(type=socket.SOCK_DGRAM) sk.sendto(b'hi',('127.0.0.1',9040)) #发给谁一条消息 msg_r,addr = sk.recvfrom(1024) print(msg_r) sk.close()
UDP:多人聊天:
服务器:
import socket sk = socket.socket(type=socket.SOCK_DGRAM) # udp协议 sk.bind(('127.0.0.1',9090)) while 1: msg_r,addr = sk.recvfrom(1024) # 接收来自哪里的消息 msg_r = msg_r.decode('utf-8') print(msg_r) if msg_r == 'q': # 如果当前客户端想要断开连接 continue # 服务器端不应该继续通话了,应该等待接收另一个客户端的连接,返回到recvfrom msg_s = input('>>>') sk.sendto(msg_s.encode('utf-8'), addr) if msg_s == 'q': break sk.close()
客户端:
import socket sk = socket.socket(type=socket.SOCK_DGRAM) while 1: msg_s = input('>>>') sk.sendto(msg_s.encode('utf-8'),('127.0.0.1',9090))# 发给谁一条消息 if msg_s is 'q': break msg_r,addr = sk.recvfrom(1024) msg_r = msg_r.decode('utf-8') print(msg_r) if msg_r == 'q': break sk.close()
UDP带颜色版多人聊天:
服务器:
import socket sk = socket.socket(type=socket.SOCK_DGRAM) # udp协议 sk.bind(('127.0.0.1',9090)) dic = {'alex':'