1. 程式人生 > 程式設計 >Python socket模組方法實現詳解

Python socket模組方法實現詳解

這篇文章主要介紹了Python socket模組方法實現詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

socket ssh (不帶防止粘包的方法)

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Ian Ying
# mail: [email protected]

import socket
import os

server = socket.socket()
server.bind(('localhost',6969)) #繫結被監聽埠
server.listen(5)  #監聽埠
while True:
  print("我要開始等電話了")
  conn,addr = server.accept() # 就是等待的意思
  #conn就是客戶端連過來的時候,在伺服器端為其生成的一個連線例項
  print("電話來了%s"% [conn,addr])
  while True:
    data = conn.recv(1024)
    if not data:
      print('client is lost.')
      break
    # res = os.popen(data).read() #popen就是開啟命令執行,read就是獲取結果
    # with open('filename','r') as ret: #這兩行就 可以用過來傳輸檔案了。
    #   data = ret.read()
    print('receive:',data)
    conn.send(data.upper())
server.close()

socket client 模組

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Ian Ying
# mail: [email protected]

import socket


client = socket.socket() #宣告socket型別,同時生成socket連結物件
client.connect(('localhost',6969))  #localhost就是本機地址

while True:
  msg = input('input msg >>:').strip()
  if len(msg) == 0: continue #檢查msg的資訊,防止無輸入資訊
  #client.send(b"Hello,world!") #傳送資訊
  client.send(msg.encode('utf-8'))

  data = client.recv(1024) #預設接受1024位元組,就是1k
  # with open('filename','w') as ret: # 這兩行就 可以用過來傳輸檔案了。
  #   ret = data.write()
  print(data.decode())
client.close() #關閉埠

防止粘包的socket_ssh.py

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Ian Ying
# mail: [email protected]

import socket
import os

server = socket.socket()
server.bind(('localhost',addr = server.accept() # 就是等待的意思
  #conn就是客戶端連過來的時候,在伺服器端為其生成的一個連線例項

  while True:
    data = conn.recv(1024).decode()
    print("電話來了%s" % type(data))
    # if type(data) is str:
    #   data = data.strip()
    if not data:
      print('client is lost.')
      break
    cmd_res = os.popen(data).read() #popen就是開啟命令執行,read就是獲取結果
    cmd_res_size = str(len(cmd_res.encode("utf-8")))
    print("before send",len(cmd_res),"size after encode",cmd_res_size)
    if len(cmd_res) == 0:
      print("there is no output.")
      res_warning = "there is no output."
      conn.send(res_warning.encode("utf-8"))
      continue
    else:
      conn.send(cmd_res_size.encode("utf8"))
      print(conn.recv(1024).decode()) #通過接收資料的形式來強制傳送緩衝區的資料,防止粘包。
    # with open('filename','r') as ret: #這兩行就 可以用過來傳輸檔案了。
    #   data = ret.read()
    #print('receive:',data)
    print('receive:',data)
    conn.send(cmd_res.encode("utf-8"))
    # conn.send(bytes(cmd_res)) #不可行。傳輸的時候是需要encoding
server.close()

socket_client.py

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Ian Ying
# mail: [email protected]

import socket


client = socket.socket() #宣告socket型別,同時生成socket連結物件
client.connect(('localhost',world!") #傳送資訊
  client.send(msg.encode('utf-8'))
  received_size = client.recv(1024).decode() #用來記錄接受的資料大小
  print("接收的資料大小",received_size)
  received_cont = b''
  received_cont_size = 0 # 用來判斷接受資料的大小
  if received_size != "there is no output." :
    client.send("準備好了,可以傳送。".encode()) #傳送確認資訊,以防止粘包
    received_size = int(received_size) #資料需要變成int才能進行判斷
    while received_size != received_cont_size: #判斷encode後的長度是否一致。
      received_cont_for_test = client.recv(1024)
      received_cont_size += int(len(received_cont_for_test))
      received_cont = received_cont + received_cont_for_test
      print("當前結束後的資料大小為:",received_cont_size)
      # print(received_cont_size)
    else:
      print("資料接收完成,接收的資料大小為:",received_cont_size)
      print("接收的內容為:\n",received_cont.decode(),"\n")
  else:
    print("output:\n",received_size)
    # data = client.recv(1024) #預設接受1024位元組,就是1k
    # with open('filename','w') as ret: # 這兩行就 可以用過來傳輸檔案了。
    #   ret = data.write()
    # print(data.decode())
    # print(str(data))
client.close() #關閉埠

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。