Python中的socket如何使用?

來源:互聯網
上載者:User

標籤:

本文和大家分享的主要是python 中socket相關內容,一起來看看吧,希望對大家 學習python有所協助。 一. 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 exceptiondup() --  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 optionsgettimeout() --  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 addressrecvfrom_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 directionsif_nameindex() --  return all network interface indices  and namesif_nametoindex(name) --  return the corresponding interface  indexif_indextoname( index) --  return the corresponding interface name
  • not available on all platforms!
  •  二. 簡單的聊天機器人如果發送一個資料,伺服器就會給他回複一個資料 +  你好1 # -*- coding:utf-8 -*-2 # zhou3 # 2017/7/345  import socket6 #  建立一個 server 對象7 server_obj = socket.socket()8 #  綁定一下連接埠9 server_obj.bind(("127.0.0.1", 8888, ))10 #  設定監聽的等待隊列長度為 5, 當大於 5 的時候就拒絕串連11 server_obj.listen(5)1213  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’: breakret = str(client.recv(1024),  encoding=’utf-8’)print(ret)client 三. 簡單的ftp上傳實現了將一個圖片上傳到伺服器端1 # -*- coding:utf-8 -*-2 # zhou3 # 2017/7/245  import socket67 server = socket.socket()8 server.bind(("127.0.0.1", 9998, ))  #  綁定 ip9 server.listen(5)1011  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()   #  關閉檔案ftpserver1 # -*- coding:utf-8 -*-2 # zhou3 # 2017/7/2456  import os7  import socket89 client = socket.socket()1011 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中的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.