大家好,又见面了,我是你们的朋友全栈君。
1、python socket模块内置方法
2、tcp服务器伪代码
3、tcp客户端伪代码
4、socket模块属性
5、一个简单的tcp客户端和服务端
服务端代码:
代码语言:javascript复制# 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()
客户端代码:
代码语言:javascript复制# 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()
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/155960.html原文链接:https://javaforall.cn