Python3 基于TCP的通信

2018-01-31  本文已影响0人  叶落思念谁

最近一段儿时间在学习Python,在这和大家分享一下Python的TCP通信,自己做了一个简单的链接代码

在先启动服务端然后启动客户端在链接后会有显示已经链接,然后在客户端发送消息服务端给你返回信息。

话不多说直接上代码,有需要的可以来看看

服务器端代码:

#!/usr/bin/env python

from socketimport *

import platform

host ='127.0.0.1'

port =12345

bufsiz =1024

tcpSerSock = socket(AF_INET, SOCK_STREAM)

tcpSerSock.bind((host, port))

tcpSerSock.listen(5)

while True:

print('Waiting for the link......')

tcpCliSock, addr = tcpSerSock.accept()

print('连接成功', tcpCliSock)

print('连接成功', addr)

print ("系统cpu位数: %s " % platform.processor())

print ("系统信息: %s " % platform.system())

print ("操作系统类型: %s" % platform.dist()[1])

print ("系统主机名: %s " % platform.node())

while True:

data = tcpCliSock.recv(1024)

print(data)

if data ==b'1':

tcpCliSock.send(platform.node().encode('utf-8'))

elif data ==b'2':

fpath ='E:\myPython\module_bacnetclientexample.xml'  # 可以返回文件以及任何格式的数据给客户端,但是数据是从文件读的

            with open(fpath, 'r')as f:

read_file = f.read()

print(read_file)

b2 =bytes(read_file, encoding='utf-8')

print(b2)

tcpCliSock.send(b2)

elif data ==b'3':

tcpCliSock.send(host.encode('utf-8'))

elif data ==b'4':

tcpCliSock.send('return is Iam '.encode('utf-8'))

else:

tcpCliSock.send("Input is wrong".encode('utf-8'))

tcpCliSock.close()

tcpSerSock.close()

客户端代码:

#!/usr/bin/env python

from socketimport *

host ='127.0.0.1'

port =12345

bufsiz =1024

tcpCliSock = socket(AF_INET, SOCK_STREAM)# 开启套接字

tcpCliSock.connect((host, port))# 连接到服务器

print('I - Send WhoIs Message')

while True:

try:

data =int(input('发送指令 >> '))# 等待输入指令

        print('WhoIs message')

print('sennd request to', host)

tcpCliSock.send(str(data).encode("utf-8"))# 发送信息

        response = tcpCliSock.recv(1024)# 接受返回信息

        print(" Got message from", response)

except:

print("Input is wrong")

tcpCliSock.close()


上一篇 下一篇

猜你喜欢

热点阅读