Python核心编程(网络编程)

时间:2023-03-10 03:00:27
Python核心编程(网络编程)

1、python socket模块内置方法

Python核心编程(网络编程)

Python核心编程(网络编程)

2、tcp服务器伪代码

Python核心编程(网络编程)

3、tcp客户端伪代码

Python核心编程(网络编程)

4、socket模块属性

Python核心编程(网络编程)

Python核心编程(网络编程)

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核心编程(网络编程)