Python系列8之socket

來源:互聯網
上載者:User

標籤:span   rom   --   for   ftpclient   blocking   option   ons   arguments   

目錄

  socket  

  簡單的聊天機器人

  簡單的ftp上傳

  粘包問題的解決

一. socket模組

  socket,俗稱通訊端,其實就是一個ip地址和連接埠的組合。類似於這樣的形式(ip,  port),其中ip代表的是某個主機,port代表的是某個應用,我們可以通過socket和另外的一台主機進行通訊。

  關於socket源碼的解析在tarnado系列文章中,正在寫中。。。。。

  1. 通訊的方式

    tcp通訊

    udp通訊

    基於unix的通訊

   2. socket的方法 
# 暫時知道的也就這麼多,之後要是在用到其他的我會繼續進行儲存    Methods of socket objects (keyword arguments not allowed):        _accept() -- accept connection, returning new socket fd and client address    bind(addr) -- bind the socket to a local address 給本地地址綁定一個socket通訊端    close() -- close the socket 關閉一個通訊端    connect(addr) -- connect the socket to a remote address     串連到遠端主機    connect_ex(addr) -- connect, return an error code instead of an exception    dup() -- return a new socket fd duplicated from fileno()    fileno() -- return underlying file descriptor    getpeername() -- return remote address [*]    getsockname() -- return local address    getsockopt(level, optname[, buflen]) -- get socket options    gettimeout() -- return timeout or None    listen([n]) -- start listening for incoming connections    recv(buflen[, flags]) -- receive data   接受資料    recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)    接受資料到緩衝區中,    recvfrom(buflen[, flags]) -- receive data and sender‘s address    recvfrom_into(buffer[, nbytes, [, flags])      -- receive data and sender‘s address (into a buffer)    sendall(data[, flags]) -- send all data 發送資料給遠端主機,3.x之後只能發送位元組形式,因此在發送的時候一般要進行轉換bytes    send(data[, flags]) -- send data, may not send all of it 也是發送資料,區別在於send發送的不完整,隨機進行發送的,二sendall發送的完整    sendto(data[, flags], addr) -- send data to a given address 基於udp發送資料的    setblocking(0 | 1) -- set or clear the blocking I/O flag    是否設定成阻塞模式0 代表阻塞,1代表非阻塞    setsockopt(level, optname, value) -- set socket options     設定一些socket的桉樹    settimeout(None | float) -- set or clear the timeout    設定逾時市場    shutdown(how) -- shut down traffic in one or both directions        if_nameindex() -- return all network interface indices and names    if_nametoindex(name) -- return the corresponding interface index    if_indextoname(index) -- return the corresponding interface name      [*] not available on all platforms!
二. 簡單的聊天機器人

  如果發送一個資料,伺服器就會給他回複一個資料 + 你好

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/3 4  5 import socket 6 # 建立一個server對象 7 server_obj = socket.socket() 8 # 綁定一下連接埠 9 server_obj.bind(("127.0.0.1", 8888, ))10 # 設定監聽的等待隊列長度為5,當大於5的時候就拒絕串連11 server_obj.listen(5)12 13 while True:14     # 等待接受用戶端的串連,為阻塞方式15     conn, address = server_obj.accept()16     # 發送歡迎資訊17     conn.sendall(bytes("歡迎來到簡單的聊天室..", encoding=‘utf-8‘))18     while True:19         # 接受到對面的訊息就會把對面訊息後面加上你好重新發送回去20         ret = str(conn.recv(1024), encoding=‘utf-8‘)21         if ret == ‘q‘:22             # 如果對面發送的為q就退出23             break24         conn.sendall(bytes(ret + ",你好", encoding=‘utf-8‘))
server
# -*- coding:utf-8 -*-# zhou# 2017/7/3import socketclient = socket.socket()client.connect(("127.0.0.1", 8888, ))# 接受歡迎資訊並列印ret = str(client.recv(1024), encoding=‘utf-8‘)print(ret)while True:    message = input("請輸入您要發送的內容:")    client.sendall(bytes(message, encoding=‘utf-8‘))    if message == ‘q‘:        break    ret = str(client.recv(1024), encoding=‘utf-8‘)    print(ret)
client

 

三. 簡單的ftp上傳

  實現了將一個圖片上傳到伺服器端

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/2 4  5 import socket 6  7 server = socket.socket() 8 server.bind(("127.0.0.1", 9998, ))  # 綁定ip 9 server.listen(5)10 11 while True:12     conn, address = server.accept()13     # 串連之後首先接收檔案大小14     file_size = int(str(conn.recv(1024), encoding=‘utf-8‘))15     # 用來解決粘包問題的16     conn.sendall(bytes("1001", encoding=‘utf-8‘))17     # 已經接受的檔案大小18     has_size = 019     num = 120     # 串連之後接收檔案21     f = open("new.jpg", ‘wb‘)22     while True:23         num += 124         if file_size == has_size:25             break26         data = conn.recv(1024)27         f.write(data)28         has_size += len(data)29     f.close()   # 關閉檔案
ftpserver

 

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/2 4  5  6 import os 7 import socket 8  9 client = socket.socket()10 11 client.connect(("127.0.0.1", 9998), )12 # 傳送檔案大小13 file_size = os.stat("1.jpg").st_size14 print(file_size)15 # 傳送檔案大小16 client.sendall(bytes(str(file_size), encoding=‘utf-8‘))17 client.recv(1024)   # 解決粘包問題18 # 傳送檔案19 with open("1.jpg", ‘rb‘) as f:20     for line in f:21         client.sendall(line)22 client.close()
ftpclient

 

四. 粘包問題的解決

  對於上面第三個ftp上傳進行的描述,

  解決粘包的問題,當我們上傳一個檔案的時候,首先上傳他的大小,當我們上傳完大小之後要在寫一句接受的語句,而伺服器端在接受到檔案大小之後要給我們立馬發送一個資料用來確認,這樣我們就可以完美的將資料喝大小分割開了。

  

 

Python系列8之socket

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.