server 代码
# coding: utf-8
import socketserver
class Handler_TCPServer(socketserver.BaseRequestHandler):
"""
The TCP Server class for demonstration.
Note: We need to implement the Handle method to exchange data
with TCP client.
"""
def handle(self):
# self.request - TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} sent:".format(self.client_address[0]))
print(self.data)
# just send back ACK for data arrival confirmation
self.request.sendall("ACK from TCP Server".encode())
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 8305
# Init the TCP server object, bind it to the localhost on 9999 port
tcp_server = socketserver.TCPServer((HOST, PORT), Handler_TCPServer)
# Activate the TCP server.
# To abort the TCP server, press Ctrl-C.
tcp_server.serve_forever()
client 代码:
# coding: utf-8
import socket
from multiprocessing import Process
def craw(index):
host_ip, server_port = "localhost", 8305
data = "Hello how are you?\n"
# Initialize a TCP client socket using SOCK_STREAM
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_client.connect((host_ip, server_port))
for i in range(100):
# try:
# Establish connection to TCP server and exchange data
data = "process:{},index:{},".format(index, i) + data
tcp_client.sendall(data.encode())
# Read data from the TCP server and close the connection
received = tcp_client.recv(1024)
# finally:
# tcp_client.close()
print("process:{},index:{},Bytes Sent: {}".format(index, i, data))
print("process:{},index:{} Bytes Received: {}".format(index, i, received.decode()))
if __name__ == '__main__':
p1 = Process(target=craw, args=(1,))
p2 = Process(target=craw, args=(2,))
p1.start()
p2.start()
p1.join()
p2.join()
print("Complete")
错误
Traceback (most recent call last):
File "C:\Python37\lib\multiprocessing\process.py", line 297, in _bootstrap
self.run()
File "C:\Python37\lib\multiprocessing\process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "F:\Seafile\Nutstore\pycode2\learnqt\tcpcode\tcp_client.py", line 20, in craw
received = tcp_client.recv(1024)
ConnectionAbortedError: [WinError 10053] 你的主机中的软件中止了一个已建立的连接。
这是什么问题?我使用多进程 socket 的方式有问题?或者应该怎么使用呢?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.