一直搞不懂这个 sock.recv()有什么用,在实践中该怎么规定大小。于是我自作聪明的把 1024 改为了 4 。然后我就贴代码了。
client.py
# -*- coding: utf-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9999))
print(s.recv(1024).decode('utf-8'))
for data in [b'12345', b'67890']:
s.send(data)
print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()
Output
Welcome!
Hello, 1234!
Hello, 5!
server.py
# -*- coding: utf-8 -*-
import socket, threading, time
def tcplink(sock, addr):
print('Accept new connection from %s:%s' % addr)
sock.send(b'Welcome!')
while True:
data = sock.recv(4)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
sock.close()
print('Connection from %s:%s closed' % addr)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(5)
print('Waiting for connection')
while True:
sock, addr = s.accept()
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
Output
Waiting for connection
Accept new connection from 127.0.0.1:59877
Exception in thread Thread-1:
Traceback (most recent call last):
File "D:\Program Files\Python35\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "D:\Program Files\Python35\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\xxxx\Desktop\server.py", line 9, in tcplink
data = sock.recv(4)
ConnectionAbortedError: [WinError 10053] 你的主机中的软件中止了一个已建立的连接。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.