python socket 收发数据

python 使用socket 服务器网络通信

socket send 无法通信和recv数据乱码

方法

#decode把字节流(bytes)转换成str
#encode把str转换成bytes

 print(">>DATA IS ",recvDate.decode("gb2312","utf-8"))
 m="DAA:d----AAi".encode()

代码python实现

#创建套接字
#bind ip and 端口
#listen 监听
# accept   waiting for the customer
#recv/send data
...

from socket import * #import socket

#1creat socket

tcpSocket=socket(AF_INET, SOCK_STREAM)#The creation format is fixed

#bind ip and 端口
address=('',8899)#parameter ip and 端口
tcpSocket.bind(address)

#listen  接受其他 的连接
tcpSocket.listen(5)



# 循环来检查客服端是否创建链接`
while (10):
    # 接受用户创建的客户端 accept return is 元组两个元素
    newSocket,clientAddress=tcpSocket.accept()


    while(1):#循环来接受客户数据
    #recvf data form customer
        recvDate=newSocket.recv(1024)
        print(">>DATA IS ",recvDate.decode("gb2312","utf-8"))#decode是吧字节流转换成str
    
     
     #sent data to customer
        m="DAA:d----AAi".encode()#encode是吧str装换成bytes
        newSocket.send(m)
        print("______")

        # close socket
    newSocket.close()

    # close listen
tcpSocket.close()



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值