前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 多进程socket

python 多进程socket

作者头像
用户5760343
发布2022-05-13 10:03:29
2630
发布2022-05-13 10:03:29
举报
文章被收录于专栏:sktjsktj

""" Server side: open a socket on a port, listen for a message from a client, and send an echo reply; forks a process to handle each client connection; child processes share parent's socket descriptors; fork is less portable than threads--not yet on Windows, unless Cygwin or similar installed; """

import os, time, sys from socket import * # get socket constructor and constants myHost = '' # server machine, '' means local host myPort = 50007 # listen on a non-reserved port number

sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object sockobj.bind((myHost, myPort)) # bind it to server port number sockobj.listen(5) # allow 5 pending connects

def now(): # current time on server return time.ctime(time.time())

activeChildren = [] def reapChildren(): # reap any dead child processes while activeChildren: # else may fill up system table pid, stat = os.waitpid(0, os.WNOHANG) # don't hang if no child exited if not pid: break activeChildren.remove(pid)

def handleClient(connection): # child process: reply, exit time.sleep(5) # simulate a blocking activity while True: # read, write a client socket data = connection.recv(1024) # till eof when socket closed if not data: break reply = 'Echo=>%s at %s' % (data, now()) connection.send(reply.encode()) connection.close() os._exit(0)

def dispatcher(): # listen until process killed while True: # wait for next connection, connection, address = sockobj.accept() # pass to process for service print('Server connected by', address, end=' ') print('at', now()) reapChildren() # clean up exited children now childPid = os.fork() # copy this process if childPid == 0: # if in child process: handle handleClient(connection) else: # else: go accept next connect activeChildren.append(childPid) # add to active child pid list

dispatcher()

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档