tags:
categories:
# socker_server.py
import socket
# 获得socket服务器端实例
server = socket.socket()
# 绑定ip port("IP", port)
server.bind(("0.0.0.0", 8888))
# 开始监听
server.listen()
print("等待客户端的连接...")
# 接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
conn, addr = server.accept()
print("新连接:", addr)
data = conn.recv(1024)
print("收到消息:", data.decode("utf-8"))
# 已经收到信息
conn.send("已经收到".encode("utf-8"))
server.close()
import socket
# 获得socket客户端实例
client = socket.socket()
client.connect(("localhost", 8888))
client.send("你好".encode("utf-8"))
# 接受服务器发送的信息
data = client.recv(1024)
print("服务器端发送的数据为:", data.decode("utf-8"))
client.close()
# socker_server.py
import socket
# 获得socket服务器端实例
server = socket.socket()
# 绑定ip port("IP", port)
server.bind(("0.0.0.0", 8888))
# 开始监听
server.listen()
while True:
print("等待客户端的连接...")
# 接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
conn, addr = server.accept()
print("新连接:", addr)
while True:
print("等待新指令")
data = conn.recv(1024)
if not data:
print("客户端断开了...")
break
print("收到消息:", data.decode("utf-8"))
# 已经收到信息
conn.send("已经收到".encode("utf-8"))
server.close()
import socket
# 获得socket客户端实例
client = socket.socket()
client.connect(("localhost", 8888))
while True:
msg = input("输入内容:>>").strip()
# 防止发空 卡住
if len(msg) == 0: continue
client.send(msg.encode("utf-8"))
# 接受服务器发送的信息
data = client.recv(1024)
print("接受服务器端数据为:", data.decode("utf-8"))
client.close()import socket
# 获得socket客户端实例
client = socket.socket()
client.connect(("localhost", 8888))
while True:
msg = input("输入内容:>>").strip()
# 防止发空 卡住
if len(msg) == 0: continue
client.send(msg.encode("utf-8"))
# 接受服务器发送的信息
data = client.recv(1024)
print("接受服务器端数据为:", data.decode("utf-8"))
client.close()
# ssh_server.py
import socket
import os
# 获得socket实例
server = socket.socket()
# 绑定ip port
server.bind(("localhost", 9999))
server.listen()
while True:
print("等待客户端的连接...")
conn, addr = server.accept()
print("新连接:", addr)
while True:
try:
data = conn.recv(1024)
# 这种方法已经不能判断客户端断开了。需要捕获异常
# if not data:
# print("客户端断开了...")
# break
print("收到命令:", data)
# py3 里socket发送的只有bytes,os.popen又只能接受str,所以要decode一下
res = os.popen(data.decode()).read()
if len(res) == 0:
res = "cmd exec success,has not output!".encode("utf-8")
# 因为中文字符占3个字节,所以传res.encode("utf-8")的长度而不是str的长度
conn.send(str(len(res.encode("utf-8"))).encode("utf-8"))
print("等待客户ack应答...")
# 等待客户端响应 解决粘包问题
client_final_ack = conn.recv(1024)
print("客户应答:", client_final_ack.decode())
print(type(res))
# 发送端也有最大数据量限制,所以这里用sendall,相当于重复循环调用conn.send,直至数据发送完毕
print(res)
conn.sendall(res.encode("utf-8"))
except ConnectionResetError as e:
print("客户端断开连接", e)
break
server.close()
# ssh_client.py
import socket
import sys
client = socket.socket()
client.connect(("localhost",9999))
while True:
msg = input(">>:").strip()
if len(msg) == 0: continue
client.send(msg.encode("utf-8"))
# 接收这条命令执行结果的大小
res_return_size = client.recv(1024)
print("getting cmd result , ", res_return_size)
total_rece_size = int(res_return_size)
print("total size:", res_return_size)
client.send("准备好接收了".encode("utf-8"))
# 已接收到的数据
received_size = 0
cmd_res = b''
# 代表还没收完
while received_size != total_rece_size:
data = client.recv(1024)
# 为什么不是直接1024,还判断len干嘛,注意,实际收到的data有可能比1024少
received_size += len(data)
cmd_res += data
else:
print("数据收完了", received_size)
print(cmd_res.decode())
client.close()
import socket
from urllib.parse import urlparse
def get_url(url):
url = urlparse(url)
host = url.netloc
path = url.path
if path == "":
path = "/"
# 建立socket连接
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# client.setblocking(False)
# 阻塞不会消耗cpu
client.connect((host, 80))
# 不停的询问连接是否建立好, 需要while循环不停的去检查状态
# 做计算任务或者再次发起其他的连接请求
client.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host).encode("utf8"))
data = b""
while True:
d = client.recv(1024)
if d:
data += d
else:
break
data = data.decode("utf8")
# 获取网站正文 去掉头部
html_data = data.split("\r\n\r\n")[1]
print(html_data)
client.close()
if __name__ == "__main__":
import time
start_time = time.time()
get_url("https://www.baidu.com")
print(time.time()-start_time)
import socketserver
# 定义自己的sockserver请求处理类
class MyTCPHandler(socketserver.BaseRequestHandler):
# 重写handle函数,跟客户端所有的交互都是在handle中写的
def handle(self):
while True:
try:
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# 下面方法行不通。需要捕获异常
# if not self.data:
# print(self.client_address, "断开了")
# break
self.request.sendall(self.data.upper())
except ConnectionResetError as e:
print(self.client_address, "断开了")
break
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# 设置ip 和端口号 并把自定义的类填入
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
import socket
client = socket.socket()
client.connect(('localhost', 9999)) # 连接服务器
while True:
msg = input(">>:").strip()
if len(msg) == 0: continue
client.send(msg.encode()) # 发送数据
data = client.recv(1024) # 接收数据
print("返回数据:", data.decode())
client.close()
import socketserver
# 定义自己的sockserver请求处理类
class MyTCPHandler(socketserver.BaseRequestHandler):
# 重写handle函数,跟客户端所有的交互都是在handle中写的
def handle(self):
while True:
try:
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# 下面方法行不通。需要捕获异常
# if not self.data:
# print(self.client_address, "断开了")
# break
self.request.sendall(self.data.upper())
except ConnectionResetError as e:
print(self.client_address, "断开了")
break
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# 设置ip 和端口号 并把自定义的类填入, 修改CPServer改成ThreadingTCPServer
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()