说明
1.需要对send 和recv的内容进行decode()和encode(),否则会报错,即使在.py最上面添加# -*- coding: utf-8 -*-
该部分内容为转载 ========================= 在StackOverflow上发现有人也出现同样的问题,并一个叫Scharron的人提出了解答: In python 3, bytes strings and unicodestrings are now two different types. Since sockets are not aware of string encodings, they are using raw bytes strings, that have a slightly differentinterface from unicode strings. So, now, whenever you have a unicode stringthat you need to use as a byte string, you need toencode() it. And whenyou have a byte string, you need to decode it to use it as a regular(python 2.x) string. Unicode strings are quotes enclosedstrings. Bytes strings are b"" enclosed strings When you use client_socket.send(data),replace it by client_socket.send(data.encode()). When you get datausing data = client_socket.recv(512), replace it by data =client_socket.recv(512).decode() Codec.encode(input[, errors]) Encodes the object input and returns atuple (output object, length consumed). Encoding converts a string object to abytes object using a particular character set encoding Codec.decode(input[, errors]) Decodes the object input and returns atuple (output object, length consumed). Decoding converts a bytes objectencoded using a particular character set encoding to a string object. input must be a bytes object or one whichprovides the read-only character buffer interface – for example, buffer objectsand memory mapped files. 套接字的成员函数send socket.send(bytes[, flags]) 形参为字节类型 socket.recv(bufsize[, flags]) Receive datafrom the socket. The return value is a bytes object representing the data received. |
str->bytes:encode编码
bytes->str:decode解码
str.encode()
bytes.decode()
socket服务端
# -*- coding: utf-8 -*- from socket import * from time import ctime HOST = '10.69.141.11' #主机(服务器)地址 PORT = 20000 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) # 创建套接字 tcpSerSock.bind(ADDR) # 监听 tcpSerSock.listen( 5 ) while True : print 'wating for connection...' tcpCliSock,addr = tcpSerSock.accept() #被动接收连接 print '...connected from:' ,addr while True : data = tcpCliSock.recv(BUFSIZE).decode() #接收来自客户端的数据 if data = = 'exit' : break print data #输出客户端的数据 sersay = raw_input ( "what do you want to say" ) tcpCliSock.send( '%s' % (sersay).encode()) #返回给客户端的数据 发送给客户端的代码必须编码 tcpCliSock.close() tcpSvrSock.close() |
socket客户端
# -*- coding: utf-8 -*- from socket import * HOST = '10.69.141.11' PORT = 20000 #IP地址一致,指向服务器地址PORT = 20000 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) while True : data = input () print ( "so %s old" % data ) if data = = 'exit' : break tcpCliSock.send(data.encode()) #发送给服务器的数据 data = tcpCliSock.recv(BUFSIZE).decode() #接收数据 if data = = 'exit' : break print (data) tcpCliSock.close() |