溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

socket模塊如何在Python項目中使用

發(fā)布時間:2021-03-18 16:00:59 來源:億速云 閱讀:154 作者:Leah 欄目:開發(fā)技術(shù)

socket模塊如何在Python項目中使用?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

socket ssh

import socket
import os

server = socket.socket()
server.bind(('localhost', 6969)) #綁定被監(jiān)聽端口
server.listen(5)  #監(jiān)聽端口
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就是打開命令執(zhí)行,read就是獲取結(jié)果
    # 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: kongqing.ying@yitu-inc.com

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!") #發(fā)送信息
  client.send(msg.encode('utf-8'))

  data = client.recv(1024) #默認接受1024字節(jié),就是1k
  # with open('filename', 'w') as ret: # 這兩行就 可以用過來傳輸文件了。
  #   ret = data.write()
  print(data.decode())
client.close() #關(guān)閉端口

防止粘包的socket_ssh.py

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Ian Ying
# mail: kongqing.ying@yitu-inc.com

import socket
import os

server = socket.socket()
server.bind(('localhost', 6969)) #綁定被監(jiān)聽端口
server.listen(5)  #監(jiān)聽端口
while True:
  print("我要開始等電話了")
  conn, 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就是打開命令執(zhí)行,read就是獲取結(jié)果
    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()) #通過接收數(shù)據(jù)的形式來強制發(fā)送緩沖區(qū)的數(shù)據(jù),防止粘包。
    # 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)) #不可行。傳輸?shù)臅r候是需要encoding
server.close()

socket_client.py

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author Ian Ying
# mail: kongqing.ying@yitu-inc.com

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!") #發(fā)送信息
  client.send(msg.encode('utf-8'))
  received_size = client.recv(1024).decode() #用來記錄接受的數(shù)據(jù)大小
  print("接收的數(shù)據(jù)大小", received_size)
  received_cont = b''
  received_cont_size = 0 # 用來判斷接受數(shù)據(jù)的大小
  if received_size != "there is no output." :
    client.send("準備好了,可以發(fā)送。".encode()) #發(fā)送確認信息,以防止粘包
    received_size = int(received_size) #數(shù)據(jù)需要變成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("當前結(jié)束后的數(shù)據(jù)大小為:", received_cont_size)
      # print(received_cont_size)
    else:
      print("數(shù)據(jù)接收完成,接收的數(shù)據(jù)大小為:", received_cont_size)
      print("接收的內(nèi)容為:\n",received_cont.decode(),"\n")
  else:
    print("output:\n", received_size)
    # data = client.recv(1024) #默認接受1024字節(jié),就是1k
    # with open('filename', 'w') as ret: # 這兩行就 可以用過來傳輸文件了。
    #   ret = data.write()
    # print(data.decode())
    # print(str(data))
client.close() #關(guān)閉端口

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI