Python实现网络通信——TCP编程

TCP编程

来源:《python程序设计》第四版

作者:董付国

 

 服务器端代码

复制代码
copy
'''
connect(address)    链接远程计算机
send(bytes[,flags]) 发送数据
recv(bufsize[,flags])   发送数据
bind(address)   绑定地址
listen()    开始接听,等待客户端连接
accept()    响应客户请求
sendall()   发送全部信息
'''
'''
服务端代码
'''
import socket

words = {'how are you?':'Fine,thank you',
         'how old are you':'18',
         'what you name?':'LuoJiaHong',
         'what is you name':'LuoJIaHong',
         'where do you work':'SDIBT',
         'bye':'Bye'
         }
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定socket,服务器的ip随意,端口号是50007
s.bind((HOST,PORT))
#开始监听,变为服务器,参数表示可同时服务的客户端数量
s.listen(1)
print('Listening at port:',PORT)
#conn,是用于数据发送的套接字,就像是一把独属服务器的锁
conn,addr = s.accept()
print('Connected by',addr)
while True:
    #每次能够传输1024字节,同时转换字符
    data = conn.recv(1024).decode()
    #接收到空串,没有收到的数据,表示对方已经关闭
    if not data:
        break
    print('Received message:',data)
    conn.sendall(words.get(data,'Nothing').encode())
conn.close()
s.close()
复制代码

客户端代码

复制代码
copy
import sys
import socket
HOST = '172.26.48.1'
PORT = 50007
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    s.connect((HOST,PORT))
except Exception as e:
    print('Server not found or not open')
    sys.exit()
while True:
    c = input('Input the content you want to send:')
    s.sendall(c.encode())
    #从服务器端接收数据字节串,然后解码为字符串
    data = s.recv(1024).decode()
    print('Received:',data)
    if c.lower() == 'bye':
        break
s.close()
复制代码
posted @   不吃jiumi女孩  阅读(130)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起