gpt4 book ai didi

swift - 如何在沙盒 macOS 应用程序和脚本(或程序)之间进行通信

转载 作者:行者123 更新时间:2023-12-03 23:46:33 28 4
gpt4 key购买 nike

我需要一种在沙盒应用程序和 google chrome 的 native 消息传递主机之间进行通信的方法。我尝试了 Bonjour 服务器和 XPC 服务,但两者都存在问题。 (如果我将它们与另一个沙盒应用程序一起使用,它们会按预期工作,我可以在两个沙盒应用程序之间进行通信)

最佳答案

您始终可以使用 python 创建一个套接字服务器,并从 swift 应用程序向它发送一个 HTTP 请求,并在收到套接字时让它向 chrome 发送一条消息。
The code for a basic socket server in python is :

import socket
import sys

def get_constants(prefix):
"""Create a dictionary mapping socket module constants to their names."""
return dict( (getattr(socket, n), n)
for n in dir(socket)
if n.startswith(prefix)
)

families = get_constants('AF_')
types = get_constants('SOCK_')
protocols = get_constants('IPPROTO_')

# Create a TCP/IP socket
sock = socket.create_connection(('localhost', 10000))

print >>sys.stderr, 'Family :', families[sock.family]
print >>sys.stderr, 'Type :', types[sock.type]
print >>sys.stderr, 'Protocol:', protocols[sock.proto]
print >>sys.stderr

try:

# Send data
message = 'This is the message. It will be repeated.'
print >>sys.stderr, 'sending "%s"' % message
sock.sendall(message)

amount_received = 0
amount_expected = len(message)

while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print >>sys.stderr, 'received "%s"' % data

finally:
print >>sys.stderr, 'closing socket'
sock.close()
和服务器:
import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the address given on the command line
server_name = sys.argv[1]
server_address = (server_name, 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
sock.listen(1)

while True:
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'client connected:', client_address
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
connection.sendall(data)
else:
break
finally:
connection.close()

关于swift - 如何在沙盒 macOS 应用程序和脚本(或程序)之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62397684/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com