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()
posted on 2017-02-28 16:08 yinshoucheng 阅读(370) 评论(0) 编辑 收藏 举报