在python中跨两个程序发送数据

时间:2016-04-13 18:50:03

标签: python sockets ipc background-process

这是我的代码:

socketcheck.py

import time
import subprocess

subprocess.Popen(["python", "server.py"])

for i in range(10):
    time.sleep(2)
    print i

def print_from_server(data):
    print data

server.py

import socket
from socketcheck import print_from_server

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('localhost',3005))

client_connected = 1

while 1:
    s.listen(1)
    conn, addr = s.accept()
    data = conn.recv(1024)
    if data:
        client_connected = 0
    else: break
    if client_connected == 0:
        print 'data received'
        print_from_server(data)
        client_connected = 1
    conn.sendall(data)

client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost',3005))
s.sendall('Hello, world')
data = s.recv(1024)
#s.close()
print 'Received', repr(data)

我在这里要做的是,运行socketcheck.py,它在后台运行server.py并侦听客户端连接。因此,无论客户端发送什么数据,我都希望将其传递给socketcheck.py。这有效吗?如果是这样,那我该如何实现呢?

现在,当我尝试运行socketcheck.py时,for循环无限期地运行。

谢谢:)

编辑:

这最初我尝试作为单个程序,但在客户端连接之前,程序的其余部分不执行(阻塞),setblocking(0)程序流不会停止但是当客户端连接到服务器它不打印(做任何事情)。服务器代码看起来像这样:

导入套接字     来自socketcheck import print_from_server

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('localhost',3005))
s.setblocking(0)

while 1:
    try:
        s.listen(1)
        conn, addr = s.accept()
        conn.setblocking(0)
        data = conn.recv(1024)
        if not data: break
        print 'data received'
        conn.sendall(data)
    except:
        print 'non blocking'
print 'the lengthy program continues from here'

1 个答案:

答案 0 :(得分:0)

使用多线程可以轻松实现功能:)