实现代码如下:
#tcp协议通信
import socket,time
class TcpConnect:
def __init__(self,ip,port):
#实例化一个基于tcp的socket对象
self.mysocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#建立与{ip}:{port}端口的tcp连接
self.mysocket.connect((ip,port))
# 调用发送的方法,并对信息进行编码
def get_tcp_send(self,message):
self.mysocket.send(message.encode('gb2312'))
# 调用接收的方法,并对信息进行编码
def get_tcp_recv(self):
recvDate=self.mysocket.recv(1024)
print('接收数据:',recvDate.decode('gb2312'))
# 关闭socket连接
def back_tcp(self):
self.mysocket.close()
if __name__ == '__main__':
ip='127.0.0.1'
port=60000
a=TcpConnect(ip,port)
# 发送的内容
for i in range(3):
message = '%d你好'%i
a.get_tcp_send(message)
time.sleep(3)
time.sleep(5)
a.back_tcp()