Python socket模块方法实现详解

yipeiwu_com7年前Python基础

这篇文章主要介绍了Python socket模块方法实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

#! /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)) #绑定被监听端口
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: 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!") #发送信息
  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: kongqing.ying@yitu-inc.com

import socket
import os

server = socket.socket()
server.bind(('localhost', 6969)) #绑定被监听端口
server.listen(5)  #监听端口
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就是打开命令执行,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: 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!") #发送信息
  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() #关闭端口

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)

本文实例讲述了Python3的urllib.parse常用函数。分享给大家供大家参考,具体如下: 1、获取url参数 >>> from urllib import...

python正则实现计算器功能

本文实例为大家分享了python正则实现计算器功能的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- # Author :Gogh # @Ti...

python实现在无须过多援引的情况下创建字典的方法

本文实例讲述了python实现在无须过多援引的情况下创建字典的方法。分享给大家供大家参考。具体实现方法如下: 1.使用itertools模块 import itertools the...

python使用Queue在多个子进程间交换数据的方法

本文实例讲述了python使用Queue在多个子进程间交换数据的方法。分享给大家供大家参考。具体如下: 这里将Queue作为中间通道进行数据传递,Queue是线程和进程安全的 fro...

Python中asyncio与aiohttp入门教程

Python中asyncio与aiohttp入门教程

很多朋友对异步编程都处于“听说很强大”的认知状态。鲜有在生产项目中使用它。而使用它的同学,则大多数都停留在知道如何使用 Tornado、Twisted、Gevent 这类异步框架上,出现...