Python network programming (i).
Function: The client sends a picture to the server.
Server code:
1 #!/user/bin/env python2 #-*-coding:utf-8-*-3 ImportSocket4SK =Socket.socket ()5Sk.bind (('127.0.0.1', 8080, ))6Sk.listen (5)7 whileTrue:8Conn, address =sk.accept ()9Conn.sendall (Bytes ('Welcome to login ftp!', encoding='Utf-8'))TenFile_size = CONN.RECV (1024). Decode () OneConn.sendall (Bytes ('have received! ', encoding='Utf-8')) ATotal_size =Int (file_size) - Print(file_size) -HAS_RECV =0 thef = open ('2.jpg','WB') - whileTrue: - ifTotal_size = =HAS_RECV: - Break + Else: -data = CONN.RECV (1024) + f.write (data) AHas_recv + =len (data) atF.close ()
Client code:
#!/user/bin/env python#-*-coding:utf-8-*-ImportSocketImportOsobj=socket.socket () Obj.connect ('127.0.0.1', 8080, )) Ret_bytes= OBJ.RECV (1024) Ret_str= str (ret_bytes, encoding='Utf-8')Print(ret_str) Size= Os.stat ('1.jpg'). St_sizeobj.sendall (Bytes (str (size), encoding='Utf-8')) Obj.recv (1024) with open ('1.jpg','RB') as F: forLineinchF:obj.sendall (line) obj.close ()
Python network programming (i)