python3 多程序實現socket通訊

2022-09-07 02:21:13 字數 1541 閱讀 1556

#

-*- coding: utf-8 -*-

import

osfrom socket import *

from multiprocessing import

process

deftalk(conn):

while 1: #

迴圈通訊

try:

from_client_msg = conn.recv(1024)

ifnot from_client_msg:break

print("

程序<%s>來自客戶端的訊息:%s

" %(os.getpid(), from_client_msg))

conn.send(from_client_msg.upper())

except

:

break

conn.close()

if__name__ == '

__main__':

'''乙個程序裡開多執行緒實現socket通訊

'''server =socket()

ip_port = ("

127.0.0.1

", 8001)

server.bind(ip_port)

server.listen(5)

while 1: #

迴圈連線

conn, addr =server.accept()

p = process(target=talk, args=(conn,))

p.start()

server.close()

#程序<7412>來自客戶端的訊息:b'aaa'

#程序<6972>來自客戶端的訊息:b'bbb'

#程序<2132>來自客戶端的訊息:b'vvv'

#程序<7492>來自客戶端的訊息:b'eee'

#程序<3660>來自客戶端的訊息:b'***'

#程序<1940>來自客戶端的訊息:b'zzz'

#

-*- coding: utf-8 -*-

from socket import *client =socket()

ip_port = ("

127.0.0.1

", 8001)

client.connect(ip_port)

while 1: #

迴圈通訊

inp = input("

>>:

").strip()

ifnot inp: continue

if inp.upper() == "

q": break

client.send(inp.encode())

from_server_msg = client.recv(1024)

print("

來自服務端的訊息:

", from_server_msg)

client.close()

Python3之多程序join daemon

import os import time from multiprocessing import process,joinablequeue defproducer0 q for i in range 5 print s 生產了 s os.getpid i q.put i q.join defpr...

Python3簡單實現多工 多程序篇

python多程序實現多工 優點 穩定性高 提公升程式執行效率 image.png from multiprocessing import pool 匯入程序池模組 import os 匯入系統模組 import time 匯入時間模組 import random def to work num 列...

python3的tkinter 多程序迴圈

tkinter python3 的多執行緒。use bin python base python3 code coding utf 8 from tkinter import import threading,time import tkinter.messagebox gui視窗類 class c...