Python核心编程(网络编程)
Posted 老司机快开车
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python核心编程(网络编程)相关的知识,希望对你有一定的参考价值。
1、python socket模块内置方法
2、tcp服务器伪代码
3、tcp客户端伪代码
4、socket模块属性
5、一个简单的tcp客户端和服务端
服务端代码:
# encoding:utf-8 from socket import * from time import ctime from datetime import * # 定义tcpServer监听端口号 HOST = \'0.0.0.0\' PORT = 21567 ADDR = (HOST, PORT) BUFFSIZE=1024 # 初始化一個tcp socket tcpSvrSock = socket(AF_INET, SOCK_STREAM) tcpSvrSock.bind(ADDR) tcpSvrSock.listen(5) while True: print(\'[%s] wait for connection...\'%(datetime.now())) tcpClientSock, clientAddr = tcpSvrSock.accept() print(\'[%s] connect from: %s...\'%(datetime.now(),clientAddr)) while True: recieveData = tcpClientSock.recv(BUFFSIZE) if not recieveData: break print(\'[%s] 收到报文:%s\' %(datetime.now(),recieveData.decode(\'utf-8\'))) sendData = input(\'> \') if not sendData: break tcpClientSock.send(bytes(sendData,\'utf-8\')) tcpClientSock.close() tcpSvrSock.close()
客户端代码:
# encoding:utf-8 from socket import * from datetime import * HOST = \'127.0.0.1\' PORT = 21567 ADDR = (HOST, PORT) BUFFSIZE=1024 clientSocket=socket(AF_INET,SOCK_STREAM) clientSocket.connect(ADDR) while True: sendData=input(\'> \') if not sendData: break sendData=bytes(sendData, \'utf-8\') clientSocket.send(sendData) recieveData=clientSocket.recv(BUFFSIZE) if not recieveData: break print(recieveData.decode(\'utf-8\')) clientSocket.close()
以上是关于Python核心编程(网络编程)的主要内容,如果未能解决你的问题,请参考以下文章
分享《Python核心编程(第3版)》《Python编程入门(第3版)》高清中英文版PDF+源代码