1. 程式人生 > >socket&socket實現ftp的get方法、socketserver

socket&socket實現ftp的get方法、socketserver

socket&socket實現ftp的get方法、socketserver

首先了解socket工作原理,client-server模式


1、socket客戶端:

2、socket類型


3、socket數據流

4、實驗

(1)寫一個client

服務端啟動監聽ip和端口

admindeMacBook-Air-62:~ admin$ nc -l 1234

客戶端連接服務端,發數據,關閉socket

pycharm中添加一個socket_client.py並之行:

import socket
HOST = ‘127.0.0.1‘
PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.sendall(‘hello world‘)
s.close()

服務端退出socket

admindeMacBook-Air-62:~ admin$ nc -l 1234
hello world
admindeMacBook-Air-62:~ admin$

客戶端發送10次

socket_client10.py

#-*-coding: UTF-8 -*-
#coding=utf-8
import socket
import time
HOST = ‘127.0.0.1‘
PORT = 1234
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #元祖(網絡socket,tcp) 
s.connect((HOST,PORT))
for i in range(10):
    s.sendall(‘%s  hello, world\n‘ %i)
    time.sleep(1)
s.close()

服務端打印10次退出

admindeMacBook-Air-62:~ admin$ nc -l 1234
0  hello, world
1  hello, world
2  hello, world
3  hello, world
4  hello, world
5  hello, world
6  hello, world
7  hello, world
8  hello, world
9  hello, world
admindeMacBook-Air-62:~ admin$

(2)寫一個server

socket_server01.py

#coding=UTF-8
import socket
import time
HOST = ‘‘ #表示監聽0.0.0.0
PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #網絡,tcp
s.bind((HOST,PORT))
s.listen(1)    #一次接受一個,寫2也是一次接受一個
connect, address = s.accept()  #接受客戶端的請求,返回的是一個連結句柄connect+地址
print ‘connent‘,connect
print ‘Connected by‘, address
while 1:
    data = connect.recv(1024)
    if not data: break
    connect.sendall(data.upper())
connect.close()
admindeMacBook-Air-62:host_performance-monitor admin$ python socket_server01.py

啟動程序並查看端口

admindeMacBook-Air-62:~ admin$ netstat -an | grep 1234
tcp4       0      0  *.1234                 *.*                    LISTEN

客戶端:

socket-client for server.py

#-*-coding: UTF-8 -*-
#coding=utf-8
import socket
import time
HOST = ‘127.0.0.1‘
PORT = 1234
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #網絡socket,tcp
s.connect((HOST,PORT))
s.sendall(‘hello, world‘) #客戶端發送1024字節
data = s.recv(1024) #接受服務器發送過來的數據
s.close()
print  ‘Received‘, repr(data) #打印服務端發送過來的數據
print data


客戶端之行發送hello world,接受HELLO WORLD

python socket-client for server.py
Received ‘HELLO, WORLD‘
HELLO, WORLD
admindeMacBook-Air-62:host_performance-monitor admin$ python socket_server01.py
connent <socket._socketobject object at 0x10427ec20>
Connected by (‘127.0.0.1‘, 63878)

現在讓客戶端一直發,服務端一直接受數據,一端關閉socket連接,另一端也自動關閉連接

server端代碼基本上不變

socket_server01.py

#coding=UTF-8
import socket
import time
HOST = ‘‘ #表示監聽0.0.0.0
PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #網絡,tcp
s.bind((HOST,PORT))
s.listen(1)    #一次接受一個,寫2也是一次接受一個
connect, address = s.accept()  #接受客戶端的請求,返回的是一個連結句柄connect+地址
print ‘connent‘,connect
print ‘Connected by‘, address
while 1:
    data = connect.recv(1024)
    print data
    if not data: break
    connect.sendall(data.upper())
connect.close()


啟動server,並查看端口:

admindeMacBook-Air-62:host_performance-monitor admin$ python socket_server01.py
admindeMacBook-Air-62:~ admin$ netstat -an | grep 1234
tcp4       0      0  *.1234                 *.*                    LISTEN

client端代碼:

vim clinet_not_stop.py
#-*-coding: UTF-8 -*-
#coding=utf-8
import socket
import time
HOST = ‘127.0.0.1‘
PORT = 1234
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #網絡socket,tcp
s.connect((HOST,PORT))
while True:
s.sendall(‘hello, world‘) #客戶端發送1024字節
data = s.recv(1024) #接受服務器發送過來的數據
print data
time.sleep(1)
s.close()
admindeMacBook-Air-62:host_performance-monitor admin$ python  python clinet_not_stop.py  client接受到server大寫返回
HELLO, WORLD
HELLO, WORLD
HELLO, WORLD
HELLO, WORLD
HELLO, WORLD
HELLO, WORLD
HELLO, WORLD
HELLO, WORLD

同時可以看到server端的來自client的發送數據,全部小寫的hello world

admindeMacBook-Air-62:host_performance-monitor admin$ python socket_server01.py
connent <socket._socketobject object at 0x10baedc20>
Connected by (‘127.0.0.1‘, 64589)
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world

按ctrl+c終止傳輸


新的需求,客戶端發送命令,服務端接收命令並之行,並返回結果,客戶端使用exit或者quit,退出。

server:socket_server_command.py

#-*-coding: UTF-8 -*-
#coding=UTF-8
import socket
from subprocess import Popen,PIPE
HOST = ‘‘ #表示監聽0.0.0.0
PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #網絡,tcp
s.bind((HOST,PORT))
s.listen(1)    #一次接受一個,寫2也是一次接受一個
connect, address = s.accept()  #接受客戶端的請求,返回的是一個連結句柄connect+地址
print ‘connent‘,connect
print ‘Connected by‘, address
while 1:
    cmd = connect.recv(1024)
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    stdout = p.stdout.read()
    stderr = p.stderr.read()
    if stdout:
        connect.sendall(stdout)
    if stderr:
        connect.sendall(stderr)
    if not cmd: break
connect.close()


client:socket_clinet_command.py

#-*-coding: UTF-8 -*-
#coding=utf-8
import socket
import time
import tab #參考:http://daixuan.blog.51cto.com/5426657/1934112
HOST = ‘127.0.0.1‘
PORT = 1234
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #網絡socket,tcp
s.connect((HOST,PORT))
while True:
    cmd = raw_input("Please input cmd:").strip() #把空字符串命令去掉,做一個判斷,非空再發送
    if cmd.lower() == ‘exit‘ or cmd.lower() == ‘quit‘:
        break
    if cmd:
        s.sendall(cmd) #客戶端發送命令
        data = s.recv(1024) #接受服務器發送過來的數據
        print data
s.close()


server啟動服務:(有客戶端連接會顯示連接句柄)

admindeMacBook-Air-62:host_performance-monitor admin$ python socket_server_command.py
connent <socket._socketobject object at 0x109192de0>
Connected by (‘127.0.0.1‘, 65512)

客戶端啟動並之行命令:

admindeMacBook-Air-62:host_performance-monitor admin$ python socket_clinet_command.py
Please input cmd:date
2017年 6月10日 星期六 18時34分21秒 CST
Please input cmd:pwd
/Users/admin/Desktop/project/host_performance-monitor
Please input cmd:exit


5、實現FTP下載功能:

1、get source dest

2、重復文件,加.new

3、打印出來get下來的文件名是/tmp/hosts 還是/tmp/hosts.new

服務端:socket_server_ftp.py

#-*-coding: UTF-8 -*-
#coding=UTF-8
import socket
from subprocess import Popen,PIPE
HOST = ‘‘ #表示監聽0.0.0.0
PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #網絡,tcp
s.bind((HOST,PORT))
s.listen(1)    #一次接受一個,寫2也是一次接受一個
connect, address = s.accept()  #接受客戶端的請求,返回的是一個連結句柄connect+地址
print ‘connent‘,connect
print ‘Connected by‘, address
while 1:
    cmd = connect.recv(1024)
    cmd_list = cmd.split()
    if cmd_list[0] == ‘get‘:   #如果是get方法,讀數據
        with open(cmd_list[1]) as fd:
            while True:   #循環讀取1024字節,然後返回一個數
                data = fd.read(1024)
                connect.sendall(data)
                if not data:   #數據讀完了,跳出while循環
                    connect.sendall(‘EOF‘)
                    break
    if not cmd: break
connect.close()


客戶端:socket_clinet_ftp.py

#-*-coding: UTF-8 -*-
#coding=utf-8
import socket
import time
import tab  #參考:http://daixuan.blog.51cto.com/5426657/1934112
import os
HOST = ‘127.0.0.1‘
PORT = 1234
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #網絡socket,tcp
s.connect((HOST,PORT))
while True:
   cmd = raw_input("Please input cmd:").strip() #把空字符串命令去掉,做一個判斷,非空再發送
   if cmd.lower() == ‘exit‘ or cmd.lower() == ‘quit‘:
       break
   cmd_list = cmd.split()
   if len(cmd_list) != 3:
       print "Ex: get file1 file2"
       continue
   else:
       s.sendall(cmd) #客戶端發送命令
       if not os.path.exists(cmd_list[2]):
           dst_file = cmd_list[2]
       else:
           dst_file = cmd_list[2]+‘.new‘
       n = 1   #定義一個變量,第一次打開文件是wb方式,第二次打開文件是a(追加)的方式打開。
       while True:
           data_rev = s.recv(1024)  # 接受服務器發送過來的數據,但是服務器發送完數據,客戶端仍在等待,就會卡住。用EOF,就break
           if data_rev.endswith(‘EOF‘):
               data = data_rev[:-3]
           else:
               data = data_rev
           if n == 1:
               with open(dst_file, ‘wb‘)  as fd:
                   fd.write(data)
           else:
               with open(dst_file, ‘a‘) as fd:
                   fd.write(data)
                   print data
           n +=1
           print "destination file is %s" %dst_file
           if data_rev[-3:] == ‘EOF‘:  #如果最後三個字符是EOF,退出ftp
               break
s.close()


啟動服務端:

admindeMacBook-Air-62:host_performance-monitor admin$ python socket_server_ftp.py
connent <socket._socketobject object at 0x104ecbde0>
Connected by (‘127.0.0.1‘, 53858)

啟動客戶端:

admindeMacBook-Air-62:host_performance-monitor admin$ python socket_clinet_ftp.py
Please input cmd:get /etc/hosts /tmp/hosts
destination file is /tmp/hosts
Please input cmd:get /etc/hosts /tmp/hosts
destination file is /tmp/hosts.new


6、SocketServer

socketserver是一個類,自帶多線程

編寫一個hander類,繼承BaseRequestHander,重寫handle()方法

針對tcp還是udp生成一個server對象

調用server對象的handle_request或者sever_forver方法

本文出自 “梅花香自苦寒來!” 博客,請務必保留此出處http://daixuan.blog.51cto.com/5426657/1934168

socket&socket實現ftp的get方法、socketserver