socket-学习

2021-01-20  本文已影响0人  看不见上帝

1.一个简单的socket连接

server

import socket

class ServerBase():

    def serverTest01(self):
        self.se = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  #获取socket对象
        print(self.se)  
        self.se.bind(("127.0.0.1",8989))  # 创建服务器地址
        self.se.listen(5)  # 允许最大连接数
        print("启动服务器...")
        while True:  
            self.conn,self.address = self.se.accept()  # 添加client连接
            print(self.address)  # 打印客户端地址
            while True:
                try:
                    self.client_data = self.conn.recv(1024)
                except Exception:
                    break
                print(str(self.client_data,"utf-8"))   # 获得数据
                if not self.client_data:
                    break
                inp = "连接成功:" + str(self.client_data,"utf-8")
                self.conn.sendall(bytes(inp,encoding="utf-8"))  # 发送数据给client
        self.con.close()
        self.se.close()


if __name__ == '__main__':
    ServerBase().serverTest01()

client

import socket

class ClientBase():

    def clientTest01(self,ip_port):
        self.clientSK = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        
        self.clientSK.connect(ip_port)  # 启动客户端连接server
        while True:
            inp = input(">>>")
            if inp == "exit":
                break
            self.clientSK.sendall(bytes(inp,encoding="utf-8"))
            self.server_reply = self.clientSK.recv(1024)
            print(str(self.server_reply,"utf-8"))

        self.clientSK.close()

if __name__ == '__main__':
    ip_port = ("127.0.0.1",8989)
    ClientBase().clientTest01(ip_port)
上一篇下一篇

猜你喜欢

热点阅读