首页 > 代码库 > Python3中socket的一种实现方式

Python3中socket的一种实现方式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017-06-09 22:57
# @Author  : wlgo2108
# @Site    : 
# @File    : ConnSocket.py
# @Software: PyCharm
# @Email   : wlgo2108@126.com


from socket  import *
import struct

class ConnSocket:
    def __init__(self,ADDR = ()):
        self.addr = ADDR
        self.tcpClientSocket = socket(AF_INET,SOCK_STREAM)
        self.tcpClientSocket.connect(self.addr)

    def send_msg(self,msg ):
        HEADSIZE = 2
        msgLen = len(msg)
        # 定义struct的fmt
        fmt = ‘!cc‘ + str(msgLen) + ‘s‘
        # 字符串打包成我们系统的格式
        some = struct.pack(fmt, bytes(chr(int(msgLen / 256)),"utf-8"), bytes(chr(int(msgLen % 256)),"utf-8"), bytes(msg,"utf-8"))
        # 将字符串发送到后台
        self.tcpClientSocket.sendall(some)
        # 接收反回报文头,解析字符串返回长度
        recvlen = self.tcpClientSocket.recv(HEADSIZE)
        li = struct.unpack(‘!BB‘, recvlen)  # 返回一个元组,含两个个元素BB表示两个无符号字符
        # 计算报文长度
        recvlen = li[1] + 256 * li[0]
        # 获取报文长度的返回字符串
        data = http://www.mamicode.com/self.tcpClientSocket.recv(recvlen)"gb2312")

    def otherSendMsg(self, msg):
        HEADSIZE = 4
        # 建立socket对象
        tcpClientSocket = socket(AF_INET, SOCK_STREAM)
        # 连接到ADDR     ADDR=(HOST,PORT) 是一个元组
        tcpClientSocket.connect(self.addr)

        msgLen = len(msg)

        fmt = ‘!cc‘ + str(msgLen) + ‘s‘
        # 字符串打包成我们系统的格式
        some = struct.pack(fmt, chr(msgLen / 256), chr(msgLen % 256), msg)
        # 将字符串发送到后台
        tcpClientSocket.sendall(some)

        # 接收反回报文头,解析字符串返回长度
        recvlen = tcpClientSocket.recv(HEADSIZE)
        print
        ‘recvlen=‘, recvlen
        li, = struct.unpack(‘!BB‘, recvlen)  # 返回一个元组,含两个个元素BB表示两个无符号字符
        print
        ‘li‘, li
        recvlen = li[1] + 256 * li[0]

        # 获取返回字符串
        reply = tcpClientSocket.recv(recvlen)
        # 关闭socket
        tcpClientSocket.close()

        return reply

  

Python3中socket的一种实现方式