Python socket模块方法实现详解

作者:星辉笑 时间:2021-02-12 20:52:39 

这篇文章主要介绍了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() #关闭端口

来源:https://www.cnblogs.com/Ian-learning/p/8454597.html

标签:python,socket,模块
0
投稿

猜你喜欢

  • Python使用微信itchat接口实现查看自己微信的信息功能详解

    2021-07-29 16:07:20
  • Python读取JSON数据操作实例解析

    2021-08-11 18:27:34
  • asp DateDiff实现文字在特定时间后消失

    2011-03-11 11:11:00
  • 详解在SpringBoot如何优雅的使用多线程

    2021-07-27 13:02:39
  • SQL Server 2008中的MERGE(不仅仅是合并)

    2010-10-15 14:16:00
  • linux安装Python3.4.2的操作方法

    2022-06-17 19:19:15
  • python的列表List求均值和中位数实例

    2023-07-09 13:06:16
  • 剑走偏锋:体验ebay的AIR

    2008-11-13 11:51:00
  • python实现粒子群算法

    2021-03-20 02:27:34
  • gchart:基于google图表API的jquery组件全攻略:1、入门

    2010-01-25 12:18:00
  • python支持多继承吗

    2023-10-14 11:22:48
  • Python Pandas读取Excel日期数据的异常处理方法

    2021-12-10 11:22:55
  • python+opencv图像分割实现分割不规则ROI区域方法汇总

    2021-04-25 01:50:54
  • ASP初学者常犯的几个错误

    2007-09-07 10:19:00
  • 利用PyQt5中QLabel组件实现亚克力磨砂效果

    2023-12-13 18:33:04
  • python如何获得list或numpy数组中最大元素对应的索引

    2021-02-10 11:30:12
  • python安装教程

    2021-06-13 09:22:49
  • asp如何使用SMTP Service发送邮件?

    2010-06-05 12:43:00
  • python实现将html表格转换成CSV文件的方法

    2023-08-25 00:48:41
  • Oracle merge合并更新函数实例详解

    2023-07-23 02:45:02
  • asp之家 网络编程 m.aspxhome.com