如何使用python从客户端通过socket将数据发送到正在运行的应用程序

2024-09-29 21:45:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个接受Json数据的应用程序。现在,我希望通过python代码发送Json数据,并希望接受从应用程序发送的Json响应。那么我的服务器脚本应该包含什么,以便我可以通过Python套接字接受数据并发送到应用程序?应用程序正在端口8080上运行

import socket 
import json
import subprocess
import unittest
import time


def test():
    s1 = socket.socket()
    s1.connect(('localhost', 8080))
    print("Start check")
    d2='{"Name":"Aniket"}'
    s1.send(d2.encode())
    print (s1.recv(8192))
    s1.close()


def initializeSocket():
    s = socket.socket()
    s.bind(('localhost', 8080))
    host, port = s.getsockname()
    s.listen(5)
    print("Socket started at "+str(port))
    print("Socket ip started at "+str(host))


filePath=r"D:\temp\MyApplication.exe"

with subprocess.Popen(filePath, stdout=subprocess.PIPE) as p: 
        print ("Start") 
        initializeSocket()
        test()

Tags: 数据testimportjson应用程序localhosthostdef

热门问题