server_stocket
#coding:utf-8 import socket if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 8001)) sock.listen(5) while True: connection,address = sock.accept() try: connection.settimeout(5) buf = connection.recv(1024) if buf == '1': connection.send('welcome to server!') else: connection.send('please go out!') except socket.timeout: print 'time out' connection.close()
client.py
#coding:utf-8 import socket import time if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8001)) time.sleep(2) sock.send('1') print sock.recv(1024) sock.close()
在终端运行server.py,然后运行clien.py
出现如下错误
D:\python\project\User_project\user_virtualenv\Scripts\python.exe D:/python/project/practice/server_stocket/server_stocket.py Traceback (most recent call last): File "D:/python/project/practice/server_stocket/server_stocket.py", line 30, in <module> sock.bind(('localhost', 8001)) File "d:\python\python\Lib\socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 10048] 通常每个套接字地址(协议/网络地址/端口) Process finished with exit code 1
望解决!!!
localhost => 127.0.0.1
看不懂
@落花无情人葬月: 将localhost换成127.0.0.1