socket本质是编程接口(API),对TCP/IP的封装,TCP/IP也要提供可供程序员做网络开发所用的接口,这就是Socket编程接口;HTTP是轿车,提供了封装或者显示数据的具体形式;Socket是发动机,提供了网络通信的能力。
通过一次socket连接,返回连接时间,来测试服务器,是否开启了端口的监听 。

电报群:https://t.me/joinchat/FZtb9xfKy8KK8oDlpQPB-g
# -*- coding: utf-8 -*-
# telegram_bot_tcping.py

import logging
import socket

g_tcping_chat_id = -399166402


def check_tcping(bot, job):
    # socket.SOCK_STREAM  流式socket , 当使用TCP时选择此参数
    host = 'www.ninthclan.com'
    port = 80
    timeout = 3
    cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    address = (host, port)
    cs.settimeout(timeout)
    # cs.connect_ex(adddress)功能与connect(address)相同,但是成功返回0,失败返回error的值。
    t_status = cs.connect_ex(address)
    if 0 != t_status:
        error_msg = 'error host : %s port %d : status : %d' % (host, port, t_status)
        logging.info('error_msg : %s' % error_msg)
        bot.send_message(chat_id=g_tcping_chat_id, text=error_msg, parse_mode='Markdown')
    cs.close()


def start_tcping(job):
    logging.info('start_tcping')
    job.run_repeating(check_tcping, interval=30 * 60, first=0)

# -*- coding: utf-8 -*-
# telegram_bot_jobs.py

import logging
from telegram.ext import Updater
from datetime import datetime

import telegram_bot_tcping


def error(bot, update, err):
    logging.error('bot : %s update : %s error : %s' % (bot, update, err))


def echo(bot, update):
    logging.info("bot : %s chat_id:%d text:%s" % (bot, update.message.chat_id, update.message.text))


def start_bot():
    try:
        start_time = datetime.now()  # 获取当前datetime
        logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

        # 温顺的莱昂
        updater = Updater(token='739344882:AAF_BMyjc7S45nado1dK5E6sMt-0jYH5VMA')
        dp = updater.dispatcher
        job = updater.job_queue
        dp.add_error_handler(error)

        # #4 电报机器人-Tcping网络端口监听
        telegram_bot_tcping.start_tcping(job)

        updater.start_polling()
        logging.info('telegram bot updater start_polling...')
        updater.idle()

        end_time = datetime.now()  # 获取当前datetime
        logging.info('花费时间:%f秒' % (end_time - start_time).total_seconds())
    except BaseException as start_bot_ex:
        logging.error("telegram_bot_jobs ex : %s" % start_bot_ex)

发表评论

电子邮件地址不会被公开。 必填项已用*标注