TCP客户端编程步骤
客户端编程步骤
- 创建Socket对象
- 连接到远端服务器的IP和Port,connect()方法
- 传输数据
- 关闭连接、释放资源
简单步骤
import socket
client = socket.socket()
ipaddr = ("127.0.0.1",9988)
client.connect(ipaddr) #直连接服务器
client.send(b"hellow")
send_data = client.recv(1024) #阻塞等待
print(send_data)
client.close()
客户端类
import socket
import threading
import datetime
import logging
# FORMAT = '%%(asctime) %%(threadName)s %(thread)d %(message)s'
logging.basicConfig(level=logging.INFO)
class Clinet_Chart:
def __init__(self,ip="127.0.0.1",port=9988):
self.addr= (ip,port)
self.socker_client = socket.socket()
self.event = threading.Event()
def socket_connect(self): #启动对远程服务端的连接
self.socker_client.connect(self.addr) #连接远端服务器
self.socker_client.send(b"I`m comming")
#装备接受数据,recv时阻塞的,开启新的线程
threading.Thread(target=self.client_recv,name="client_recv").start()
def client_recv(self):
while not self.event.is_set():
try:
data = self.socker_client.recv(1024).decode("gbk") #阻塞接受
logging.info(data)
except Exception as e:
logging.info(e)
break
recv_msg = '{:%Y%m%d %H:%M:%S} {}:{}\n{}\n'.format(datetime.datetime.now(), *self.addr, data.strip())
logging.info(recv_msg)
def client_send(self,recv_msg:str):
data = "{}\n".format(recv_msg.strip()).encode() #服务端需要一个换行符
self.socker_client.send(data)
def stop(self):
self.socker_client.close()
self.event.wait(3)
self.event.set()
logging.info("client stops")
def main():
cc = Clinet_Chart()
cc.socket_connect()
while True:
cmd = input(">>>>>")
if cmd.strip() == "quit":
cc.stop()
break
cc.client_send(cmd)
if __name__ == '__main__':
main()
|