服务端 server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 8000
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print("got connection from",addr)
data = 'Thank you for connecting'
c.send(data.encode())
c.close()
客户端 client.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 8000
s.connect((host, port))
print(s.recv(1024).decode())
server运行结果:
got connection from ('10.39.3.146', 65192)
client运行结果:
Thank you for connecting
还有个python2和Python3的坑:
TypeError: a bytes-like object is required, not ‘str’
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()