python tcp服务端-客户端

 tcp服务端

#!/usr/bin/python3
# -*-coding:utf-8 -*-
from socket import *
import time
COD = ‘utf-8‘
HOST = ‘0.0.0.0‘ # 主机ip
PORT = 9999 # 端口号
BUFSIZ = 1024
ADDR = (HOST, PORT)
SIZE = 10
tcpS = socket(AF_INET, SOCK_STREAM) # 创建socket对象
tcpS.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #加入socket配置,重用ip和端口
tcpS.bind(ADDR) # 绑定ip端口号
tcpS.listen(SIZE)  # 设置最大链接数
while True:
    print("服务器启动,监听客户端链接")
    conn, addr = tcpS.accept()
    print("链接的客户端", addr)
    while True:
        try:
            data = conn.recv(BUFSIZ) # 读取已链接客户的发送的消息
        except Exception:
            print("断开的客户端", addr)
            break
        print("客户端发送的内容:",data.decode(COD))
        if not data:
            break
        msg = time.strftime("%Y-%m-%d %X") #获取结构化事件戳
        msg1 = ‘[%s]:%s‘ % (msg, data.decode(COD))
        conn.send(msg1.encode(COD)) #发送消息给已链接客户端
    conn.close() #关闭客户端链接
tcpS.close()

tcp客户端

#!/usr/bin/python3
# -*-coding:utf-8 -*-
from socket import *
from time import ctime
HOST = ‘127.0.0.1‘ #服务端ip
PORT = 9999 #服务端端口号
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM) #创建socket对象
tcpCliSock.connect(ADDR) #连接服务器
while True:
    data = input(‘>>‘).strip()
    if not data:
        break
    tcpCliSock.send(data.encode(‘utf-8‘)) #发送消息
    data = tcpCliSock.recv(BUFSIZ) #读取消息
    if not data:
        break
    print(data.decode(‘utf-8‘))
tcpCliSock.close() #关闭客户端

server

服务器启动,监听客户端链接
链接的客户端 (‘127.0.0.1‘, 56129)
客户端发送的内容: age
客户端发送的内容: name

client

>>age
[2020-03-02 00:24:09]:age
>>name
[2020-03-02 00:24:13]:name
>>

相关推荐