Python开发【第八篇】:socket网络编程
服务端:
- import socket
- server = socket.socket()
- #绑定要监听的端口
- server.bind(('localhost',6969))
- #监听
- server.listen()
- print("等待连接...")
- #等待连接,conn就是客户端连过来在服务端为其生成的一个连接实例
- conn,addr = server.accept()
- print("连接进行中...")
- print(conn,addr)
- data = conn.recv(1024)
- print("recv:",data)
- conn.send(data.upper())
- server.close()
客户端:
- import socket
- #声明socket类型,同时生产socket连接对象
- client = socket.socket()
- client.connect(('localhost',6969))
- client.send(b"hello world!")
- data = client.recv(1024)
- print("recv:",data)
- client.close()
服务端输出:
- 等待连接...
- 连接进行中...
- <socket.socket fd=328, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 6969), raddr=('127.0.0.1', 50248)> ('127.0.0.1', 50248)
- recv: b'hello world!'
客户端输出:
- recv: b'HELLO WORLD!'
连续发送信息:
服务端:
- import socket
- client = socket.socket()
- client.connect(('localhost',6969))
- while True:
- msg = input(">>:").strip()
- client.send(msg.encode("utf-8"))
- data = client.recv(1024)
- print("recv:",data.decode())
- client.close()
客户端:
- import socket
- #声明socket类型,同时生产socket连接对象
- client = socket.socket()
- client.connect(('localhost',6969))
- client.send(b"hello world!")
- # client.send("我要下载".encode("utf-8"))
- data = client.recv(1024)
- print("recv:",data)
- client.close()
在linux上客户端执行命令
服务端:
- [root@test-c2c-console01 oldboy]# cat socket_server.py
- #-*-coding:utf-8-*-
- #_author_="golden"
- #服务端
- import socket
- import os
- server = socket.socket()
- #绑定要监听的端口
- server.bind(('localhost',6969))
- #监听,最大连接数
- server.listen(5)
- print("等待连接...")
- while True:
- #conn就是客户端连过来在服务端为其生成的一个连接实例
- conn,addr = server.accept()
- print("连接进行中...")
- print(conn,addr)
- while True:
- data = conn.recv(1024)
- print("recv:",data)
- if not data:
- print("客户端断开!")
- break
- res = os.popen(data).read()
- conn.send(res)
- server.close()
客户端:
- [root@test-c2c-console01 oldboy]# cat socket_client.py
- #-*-coding:utf-8-*-
- _author_ = "golden"
- #客户端
- import socket
- #声明socket类型,同时生成socket连接对象
- client = socket.socket()
- client.connect(('localhost',6969))
- while True:
- msg = raw_input(">>:").strip()
- if len(msg) == 0:continue
- client.send(msg.encode("utf-8"))
- data = client.recv(102400)
- print(data.decode())
- client.close()
linux发送文件
服务端:
- [root@test-c2c-console01 oldboy]# cat socket_server.py
- #-*-coding:utf-8-*-
- #_author_="golden"
- #服务端
- import socket
- import os
- server = socket.socket()
- #绑定要监听的端口
- server.bind(('localhost',6969))
- #监听,最大连接数
- server.listen(5)
- print("等待连接...")
- while True:
- #conn就是客户端连过来在服务端为其生成的一个连接实例
- conn,addr = server.accept()
- print("连接进行中...")
- print(conn,addr)
- while True:
- data = conn.recv(1024)
- print("recv:",data)
- if not data:
- print("客户端断开!")
- break
- #res = os.popen(data).read()
- #conn.send(res)
- f = open("move.mkv")
- data = f.read()
- conn.send(data)
- server.close()
客户端:
- [root@test-c2c-console01 oldboy]# cat socket_client.py
- #-*-coding:utf-8-*-
- _author_ = "golden"
- #客户端
- import socket
- #声明socket类型,同时生成socket连接对象
- client = socket.socket()
- client.connect(('localhost',6969))
- while True:
- msg = raw_input(">>:").strip()
- if len(msg) == 0:continue
- client.send(msg.encode("utf-8"))
- data = client.recv(102400)
- #print(data.decode())
- f = open("video.avi",'wb')
- f.write(data)
- f.close()
- client.close()
一次最多发送的数据量32768(不同系统有区别)
- [root@test-c2c-console01 oldboy]# ll *.avi *.mkv
- -rw-r--r-- 1 root root 681790584 Dec 27 19:26 move.mkv
- -rw-r--r-- 1 root root 32768 Feb 12 08:47 video.avi
多次发送
服务端:
- [root@test-c2c-console01 oldboy]# cat socket_server.py
- #-*-coding:utf-8-*-
- #_author_="golden"
- #服务端
- import socket
- import os
- server = socket.socket() #实例化一个socket
- #绑定要监听的端口
- server.bind(('localhost',6969))
- #监听,最大连接数
- server.listen(5)
- print("等待连接...")
- while True:
- #conn就是客户端连过来在服务端为其生成的一个连接实例
- conn,addr = server.accept()
- print("连接进行中...")
- print(conn,addr)
- while True:
- data = conn.recv(1024)
- print("recv:",data)
- if not data:
- print("客户端断开!")
- break
- #res = os.popen(data).read()
- #conn.send(res)
- f = open("move.mkv")
- data = f.read()
- print(len(data))
- conn.send(data)
- server.close()
客户端:
- [root@test-c2c-console01 oldboy]# cat socket_client.py
- #-*-coding:utf-8-*-
- _author_ = "golden"
- #客户端
- import socket
- #声明socket类型,同时生成socket连接对象
- client = socket.socket()
- client.connect(('localhost',6969))
- f = open("video.avi",'wb')
- while True:
- msg = raw_input(">>:").strip()
- if len(msg) == 0:continue
- client.send(msg.encode("utf-8"))
- data = client.recv(102400)
- #print(data.decode())
- f.write(data)
- f.flush()
- client.close()
每交互一次文件的变化:
- [root@test-c2c-console01 oldboy]# ll
- total 665832
- -rw-r--r-- 1 root root 681790584 Dec 27 19:26 move.mkv
- -rw-r--r-- 1 root root 0 Feb 12 09:08 video.avi
- [root@test-c2c-console01 oldboy]# ll
- total 665864
- -rw-r--r-- 1 root root 681790584 Dec 27 19:26 move.mkv
- -rw-r--r-- 1 root root 32768 Feb 12 09:08 video.avi
- [root@test-c2c-console01 oldboy]# ll
- total 665964
- -rw-r--r-- 1 root root 681790584 Dec 27 19:26 move.mkv
- -rw-r--r-- 1 root root 135168 Feb 12 09:08 video.avi
- [root@test-c2c-console01 oldboy]# ll
- total 666164
- -rw-r--r-- 1 root root 681790584 Dec 27 19:26 move.mkv
- -rw-r--r-- 1 root root 339968 Feb 12 09:09 video.avi
- [root@test-c2c-console01 oldboy]# ll
- total 666164
- -rw-r--r-- 1 root root 681790584 Dec 27 19:26 move.mkv
- -rw-r--r-- 1 root root 339968 Feb 12 09:09 video.avi
socket实现简单的ssh
服务端:
- import socket,os
- server = socket.socket()
- server.bind(('localhost',9999))
- server.listen()
- while True:
- conn,addr = server.accept()
- print("new conn:",addr)
- while True:
- data = conn.recv(1024)
- if not data:
- print("客户端已断开!")
- break
- print("执行指令:",data)
- cmd_res = os.popen(data.decode()).read() #接收字符串,执行结果也是字符串
- print("before send ",len(cmd_res))
- if len(cmd_res) ==0:
- cmd_res = "cmd has no output"
- conn.send(str(len(cmd_res.encode())).encode("utf-8"))#先发大小给客户端
- conn.send(cmd_res.encode("utf-8"))
- server.close()
客户端:
- import socket
- client = socket.socket()
- client.connect(('localhost',9999))
- while True:
- cmd = input(">>:").strip()
- if len(cmd) == 0:continue
- client.send(cmd.encode("utf-8"))
- cmd_res_size = client.recv(1024)#接收大小
- print("结果大小:",cmd_res_size)
- received_size = 0
- received_data = b''
- while received_size < int(cmd_res_size.decode()):
- data = client.recv(1024)
- received_size += len(data) #每次收到的有可能小于1024,所以必须用len判断
- # print(data.decode())
- received_data += data
- else:
- print("cmd res receive done...",received_size)
- print(received_data.decode())
- client.close()
注意socket粘包问题。
方法一:在多个相连的send之间添加sleep。
- conn.send(str(len(cmd_res.encode())).encode("utf-8"))#先发大小给客户端
- time.sleep(0.5)
- conn.send(cmd_res.encode("utf-8"))
方法二:在每次send之后进行一次交互。
服务端:
- conn.send(str(len(cmd_res.encode())).encode("utf-8"))#先发大小给客户端client_ack = conn.recv(1024) #wait client to confirm
- print(client_ack.decode())
- conn.send(cmd_res.encode("utf-8"))
客户端:
- cmd_res_size = client.recv(1024)#接收大小
- client.send("已准备好接收数据!".encode("utf-8"))
socket实现简单的ftp
ftp server:
1、读取文件名
2、检测文件是否存在
3、打开文件
4、检测文件大小
5、发送文件大小给客户端
6、等待客户端确认
7、开始边读边发数据
8、发送md5
服务端:
- import socket,os,hashlib
- server = socket.socket()
- server.bind(("localhost",9999))
- server.listen()
- while True:
- conn,addr = server.accept()
- print("new conn:",addr)
- while True:
- print("等待指令...")
- data = conn.recv(1024)
- if not data:
- print("客户端已断开!")
- break
- cmd,filename = data.decode().split()
- print(filename)
- if os.path.isfile(filename):
- f = open(filename,"rb")
- m = hashlib.md5()
- file_size = os.stat(filename).st_size
- conn.send(str(file_size).encode()) #send file size
- conn.recv(1024) #wait for ack
- for line in f:
- m.update(line)
- conn.send(line)
- print("file md5",m.hexdigest())
- f.close()
- conn.send(m.hexdigest().encode()) #sed med5
- print("send done")
- server.close()
客户端:
- import socket,hashlib
- client = socket.socket()
- client.connect(('localhost',9999))
- while True:
- cmd = input(">>:").strip()
- if len(cmd) == 0:continue
- if cmd.startswith("get"):
- client.send(cmd.encode())
- server_response = client.recv(1024)
- print("server_response:",server_response)
- client.send(b"read to recv file")
- file_total_size = int(server_response.decode())
- received_size = 0
- filename = cmd.split()[1]
- f = open(filename + ".new","wb")
- m = hashlib.md5()
- while received_size < file_total_size:
- if file_total_size - received_size > 1024:
- size = 1024
- else:
- size = file_total_size - received_size
- data = client.recv(size)
- received_size += len(data)
- m.update(data)
- f.write(data)
- # print(file_total_size,received_size)
- else:
- new_file_md5 = m.hexdigest()
- print("file recv done",received_size,file_total_size)
- f.close()
- server_file_md5 = client.recv(1024)
- print("server file md5:{0},client file md5:{1}".format(server_file_md5,new_file_md5))
- client.close()
SocketServer
实现并发处理。
The socketserver module simplifies the task of writing network servers.
socketserver常用类型
class socketserver.TCPServer(server_address,RequestHandlerClass,bind_and_activate=True)
This uses the Internet TCP protocol,which provides for continuous streams of data between the client and server.
class socketserver.UDPServer(server_address,RequestHandlerClass,bind_and_activate=True)
This uses datagrams,which are discrete packets of information that may arrive out of order or be lost while in transit.The parameters are the same as for TCPServer.
创建一个socketserver至少分一下几步:
1、You mast create a request handler class by subclassing the BaseRequestHandler class and overriding its handle() method;this method will process incoming requests.
创建一个请求处理类继承BaseRequestHandler,并且重写父类handle()。
2、You mast instantiate one of the server classes,passing it the server's address and the request handler class.
实例化TCPServer,并传递server ip和上述创建的请求处理类给这个TCPServer。
3、Then call the handle_request() or server_forever() method of the server object to process one or many requests.
server.handle_request():只处理一个请求
server.server_forever():处理多个请求
4、Call server_close() to close the socket.
服务端:
- import socketserver
- class MyTCPHandler(socketserver.BaseRequestHandler):
- def handle(self):
- while True:
- try:
- self.data = self.request.recv(1024).strip()
- print("{} wrote :".format(self.client_address[0]))
- print(self.data)
- self.request.send(self.data.upper())
- except ConnectionResetError as CR:
- print("err",CR)
- break
- if __name__ == "__main__":
- HOST,PORT = "localhost",9999
- # server = socketserver.TCPServer((HOST,PORT),MyTCPHandler) # 单线程
- server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler) # 多线程,ForkingTCPServer多进程
- 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("utf-8"))
- data = client.recv(1024)
- print("recv:",data.decode())
- client.close()
开启一个新线程
- def process_request(self, request, client_address):
- """Start a new thread to process the request."""
- t = threading.Thread(target = self.process_request_thread,
- args = (request, client_address))
- t.daemon = self.daemon_threads
- t.start()
Python开发【第八篇】:socket网络编程的更多相关文章
- 【python自动化第八篇:网络编程】
一.拾遗 动态导入模块 目的是为了在导入模块的过程中将模块以字符的格式导入. #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:wanghui ...
- python面向对象、类、socket网络编程
类和对象 python3统一了类与类型的概念:类==类型:从一组对象中提取相似的部分就是类:特征与技能的结合体就叫做对象: 类的功能: 初始实例化: 属性引用: 1.数据属性: 2.函数属性: 对于一 ...
- python学习之路-9 socket网络编程
socket基础 socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. so ...
- Java基础篇Socket网络编程中的应用实例
说到java网络通讯章节的内容,刚入门的学员可能会感到比较头疼,应为Socket通信中一定会伴随有IO流的操作,当然对IO流比较熟练的哥们会觉得这是比较好玩的一章,因为一切都在他们的掌握之中,这样操作 ...
- python3.x 基础八:socket网络编程
Socket socket就是一直以来说的“套接字”,用于描述:ip:端口,是通信链的句柄,客户端通过这个句柄进行请求和响应 普通文件的操作顺序:打开-读写-关闭,针对的是文件 socket是特殊的文 ...
- Python之路【第七篇】python基础 之socket网络编程
本篇文章大部分借鉴 http://www.cnblogs.com/nulige/p/6235531.html python socket 网络编程 一.服务端和客户端 BS架构 (腾讯通软件:ser ...
- 从零开始学Python第八周:网络编程基础(socket)
Socket网络编程 一,Socket编程 (1)Socket方法介绍 Socket是网络编程的一个抽象概念.通常我们用一个Socket表示"打开了一个网络链接",而打开一个Soc ...
- python第八周:socket网络编程
1.socket网络编程 1.1概念: 网络套接字是跨计算机网络的连接的端点.今天,计算机之间的大多数通信都基于互联网协议;因此大多数网络套接字都是Internet套接字.更准确地说,套接字是一个句柄 ...
- Python全栈【Socket网络编程】
Python全栈[socket网络编程] 本章内容: Socket 基于TCP的套接字 基于UDP的套接字 TCP粘包 SocketServer 模块(ThreadingTCPServer源码剖析) ...
- python之Socket网络编程
什么是网络? 网络是由节点和连线构成,表示诸多对象及其相互联系.在数学上,网络是一种图,一般认为专指加权图.网络除了数学定义外,还有具体的物理含义,即网络是从某种相同类型的实际问题中抽象出来的模型.在 ...
随机推荐
- hello2 源码解析
在hello2的项目中,采用的是Java servlet 技术来采取对项目的整体框架的搭建.编写另一个greeting的java文件,实现了一个greeting的java类来覆盖url的doGet方 ...
- 安卓控制LED驱动编写
开发平台 * 芯灵思SinlinxA33开发板 淘宝店铺: https://sinlinx.taobao.com/ 嵌入式linux 开发板交流 QQ:641395230 打开Android Stud ...
- PythonStudy——Python 中Switch-Case 结构的实现
学习Python过程中,发现Python没有Switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现.所以不妨自己来实现Switch-Case功能. 方法一 ...
- php 多线程
windows下安装php真正的多线程扩展pthreads教程 http://www.thinkphp.cn/topic/22676.html PHP 安装 Pthreads (解决 class Th ...
- java_字段声明
多字段继承,为避免混淆,simple name与qualified name的使用 package java20180129_1; interface Frob { float v=2.0f; } c ...
- 数字证书的理解以及自建CA机构颁发证书
一.理解什么是数字证书 http://www.cnblogs.com/JeffreySun/archive/2010/06/24/1627247.html 理解数字证书等概念,无数次想好好看 ...
- spring cloud gateway - RequestRateLimiter
1. Official website 5.7 RequestRateLimiter GatewayFilter Factory The RequestRateLimiter GatewayFilte ...
- SpringMVC的工作流程、组件说明以及常用注解说明
1. SpringMVC处理流程 2. SpringMVC架构 2.1 框架结构 2.2 框架流程 1. 用户发送请求至前端控制器DispatcherServlet. 2. DispatcherSer ...
- dubbo文档
Srping版Dubbo集成中文地址: https://dubbo.gitbooks.io/dubbo-user-book/content/preface/background.html Spring ...
- NodeJS client code websocket
var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); client.on('co ...