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