python通过套接字来发送接收消息

案例如下:

1、启动一个服务端套接字服务

2、启动一个客户端套接字服务

3、客户端向服务端发送一个hello,服务端则回复一个word,并打印

参考地址:https://www.cnblogs.com/xilouch/p/4618903.html

服务端代码:

#coding:utf-8

import socket
import time

class Server:
    def __init__(self,host,port):
        self.port = port
        self.host = host
        self.status = 0
        self.BUF_SIZE = 1024

    def createServer(self):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((self.host, self.port))

    def startServer(self):
        self.status = 1
        self.createServer()
        #设置接收的连接数为1
        self.server.listen(1)
        client, address = self.server.accept()
        while self.status == 1:  # 循环收发数据包,长连接
            data = client.recv(self.BUF_SIZE)
            text = data.decode()
            if text != "":
                print(text)  # python3 要使用decode
                client.send("world".encode())
                # client.close() #连接不断开,长连接

if __name__ == "__main__":
    server = Server("localhost",8083)
    server.createServer()
    server.startServer()

客户端代码:

#coding:utf-8

import socket
import time
import threading


class Client:
    def __init__(self,host,port):
        self.port = port
        self.host = host
        self.status = 0
        self.BUF_SIZE = 1024

    def connect(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  # 在客户端开启心跳
        self.client.connect((self.host, self.port))

    def send(self,mes):
        client.startResv()
        while True:
            self.client.send(mes.encode())
            time.sleep(1)  # 如果想验证长时间没发数据,SOCKET连接会不会断开,则可以设置时间长一点

    def resv(self):
        while True:
            data = self.client.recv(self.BUF_SIZE)
            text = data.decode()
            print(text)

    def startResv(self):
        t = threading.Thread(target=self.resv)
        t.start()




    def close(self):
        self.client.close()


if __name__ == "__main__":
    client = Client("localhost",8083)
    client.connect()
    client.send("hello")

 运行如下图:

  

 

posted @ 2019-04-20 16:22  远洪  阅读(2654)  评论(0编辑  收藏  举报