Python实现的简单文件传输服务器和客户端
还是那个题目(题目和流程见java版本),感觉光用java写一点新意也没有,恰巧刚学习了python,何不拿来一用,呵呵:
服务器端:
import SocketServer, time class MyServer(SocketServer.BaseRequestHandler): userInfo = { 'yangsq' : 'yangsq', 'hudeyong' : 'hudeyong', 'mudan' : 'mudan' } def handle(self): print 'Connected from', self.client_address while True: receivedData = self.request.recv(8192) if not receivedData: continue elif receivedData == 'Hi, server': self.request.sendall('hi, client') elif receivedData.startswith('name'): self.clientName = receivedData.split(':')[-1] if MyServer.userInfo.has_key(self.clientName): self.request.sendall('valid') else: self.request.sendall('invalid') elif receivedData.startswith('pwd'): self.clientPwd = receivedData.split(':')[-1] if self.clientPwd == MyServer.userInfo[self.clientName]: self.request.sendall('valid') time.sleep(5) sfile = open('PyNet.pdf', 'rb') while True: data = sfile.read(1024) if not data: break while len(data) > 0: intSent = self.request.send(data) data = data[intSent:] time.sleep(3) self.request.sendall('EOF') else: self.request.sendall('invalid') elif receivedData == 'bye': break self.request.close() print 'Disconnected from', self.client_address print if __name__ == '__main__': print 'Server is started\nwaiting for connection...\n' srv = SocketServer.ThreadingTCPServer(('localhost', 50000), MyServer) srv.serve_forever()
说明:
line-55到line-58的作用就相当于java中某个类里面的main函数,即一个类的入口。
python中SocketServer module里提供了好多实用的现成的类,BaseRequestHandler就是一个,它的作用是为每一个请求fork一个线程,只要继承它,就有这个能力了,哈哈,真是美事。
当然,我们继承了BaseRequestHandler,就是override它的handle方法,就像java中继承了Thread后要实现run方法一样。实际上这个handle方法的内容和我们的java版本的run函数实现的完全一样。
line-30到line-43就是处理文件下载的主要内容了。看着都挺眼熟的呵:)
这里在文件发送完后发了一个“EOF”,告诉client文件传完了。
客户端:
import socket, time class MyClient: def __init__(self): print 'Prepare for connecting...' def connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 50000)) sock.sendall('Hi, server') self.response = sock.recv(8192) print 'Server:', self.response self.s = raw_input("Server: Do you want get the 'thinking in python' file?(y/n):") if self.s == 'y': while True: self.name = raw_input('Server: input our name:') sock.sendall('name:' + self.name.strip()) self.response = sock.recv(8192) if self.response == 'valid': break else: print 'Server: Invalid username' while True: self.pwd = raw_input('Server: input our password:') sock.sendall('pwd:' + self.pwd.strip()) self.response = sock.recv(8192) if self.response == 'valid': print 'please wait...' f = open('b.pdf', 'wb') while True: data = sock.recv(1024) if data == 'EOF': break f.write(data) f.flush() f.close() print 'download finished' break else: print 'Server: Invalid password' sock.sendall('bye') sock.close() print 'Disconnected' if __name__ == '__main__': client = MyClient() client.connect()
line-34到line-41处理文件下载,client收到server的“EOF”信号后,就知道文件传完了。
最后需要说明一下python的文件,由于是内置类型,所以不想java那样有那么多的reader,writer,input,ouput啊。python中,在打开或建立一个文件时,主要是通过模式(mode)来区别的。
python的网络编程确实简单,因为它提供了各种功能的已经写好的类,直接继承就Ok了。
python还在学习中,上面的例子跑通是没问题,但写得肯定不够好,还得学习啊

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
