This article mainly introduces the simple file transfer Server and Client implemented by Python. This article provides the implementation code of the Server and Client, if you need a friend, you can refer to the question or question (for the question and process, see the java version). I feel that I have not written any new ideas in java. I just learned python. why not use it:
Server:
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()
Note:
Line-55 to line-58 is equivalent to the main function in a class in java, that is, the entry of a class.
In python, the SocketServer module provides a lot of practical ready-made classes. BaseRequestHandler is one, and its function is to fork a thread for every request. as long as it inherits, it has this capability. haha, it's really beautiful.
Of course, we inherit the BaseRequestHandler, that is, the handle method of override, just like the run method after java inherits the Thread. In fact, the content of this handle method is exactly the same as that of the run function of our java version.
Line-30 to line-43 are the main content for processing file downloads. Looks familiar :)
Here, an "EOF" is sent after the file is sent, telling the client that the file has been uploaded.
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 to line-41 process file downloads. after the client receives the "EOF" signal from the server, it will know that the file has been uploaded.
Finally, we need to explain the python file. because it is of the built-in type, we do not want to have so many readers, writer, input, and ouput in java. In python, when opening or creating a file, the main difference is through mode.
Python's network programming is really simple, because it provides a variety of functions of the classes that have been written, it is OK to directly inherit.
Python is still learning. the above example is okay, but it is definitely not good enough to write.