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()