SOCKET 的简单使用
-
server端:
import socket so = socket.socket() #创建套接字 so.setsockopt(socket.SOL_SOCKET, soket.SO_REUSEADDR, 1) #防止端口被长期占用 so.bind( ("IP",端口)) #绑定你要开启服务的端口 so.listen() connet ,addr = so.accept() #等待链接后重新分配一个端口 # addr 为请求方的地址和端口 # connet 为重新分配的套接字,为本次连接的客户端服务 ret = connet.recv(1024) #等待接收字节数据 # 处理你的数据 print(ret) connet.close() #关闭本次连接 so.close() #关闭本程序连接
-
client端:
import socket so = socket.socket() # 创建套接字 so.connect(("IP", 端口)) # 连接要发送的地址和端口 so.send(b"字节数据") # 发送字节数据 so.close() # 关闭本次连接
-
作业:
1. 循环对话聊天 2. server: #接收时间戳时间,转换成格式化时间\ client: 每10秒钟发送一次时间戳
-
循环聊天:
1、server端: import socket Addr = "127.0.0.1" Port = 9000 so = socket.socket() so.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) so.bind((Addr, Port)) so.listen() connect, addr = so.accept() print(str(addr) + "已经连接") while True: ret = connect.recv(1024).decode("utf-8") if ret == "bye": break else: print(ret) info = input(">>>输入要发送的内容:") connect.send(bytes(info, encoding="utf-8")) connect.close() so.close() 2、client端: # coding:UTF-8 import socket Addr = "127.0.0.1" Port = 9000 so = socket.socket() so.connect((Addr, Port)) while True: info = input(">>>输入你要发送的内容:") so.send(bytes(info, encoding="utf-8")) ret = so.recv(1024).decode("utf-8") if ret == "bye": print("断开连接") break print(ret) so.close()
-
定时时间转换:
1、server端: import socket import time Addr = "127.0.0.1" Port = 9000 so = socket.socket() so.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) so.bind((Addr, Port)) so.listen() connect, addr = so.accept() while True: ret = connect.recv(1024).decode("utf-8") ret = time.localtime(float(ret)) print(time.strftime("%Y-%m-%d %H:%M:%S", ret)) connect.close() so.close() 2、client端: # coding:UTF-8 import socket import time Addr = "127.0.0.1" Port = 9000 so = socket.socket() so.connect((Addr, Port)) while True: time.sleep(10) so.send(bytes(str(time.time()), encoding="utf-8")) so.close()
网友评论