server.py
#!/usr/bin/env python #coding:utf-8 #Created by Andy @ 2017/9/14 import socket BUFSIZE = 1024 ip_port = ('127.0.0.1', 9000) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM ) s.bind(ip_port) s.listen(5) client, client_addr = s.accept() print(client, client_addr) msg = s.recv(BUFSIZE) print(msg, type(msg)) client.send(msg.upper()) client.close() s.close()
client.py
#!/usr/bin/env python #coding:utf-8 #Created by Andy @ 2017/9/14 import socket BUFSIZE = 1024 ip_port = ('127.0.0.1', 9000) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ip_port) client.send('Andy is here'.encode('utf-8')) feedback = client.recv(BUFSIZE) print(feedback.decode('utf-8')) client.close()
运行后:
可以看到问题出在s.recv(BUFSIZE)
原因就在于这里的s是服务端的套接字,而这样导致的结果是:s没有与client连接,只需要改成:msg = client.recv(BUFSIZE)
再次运行,一切正常。