python启动服务调用函数
时间: 2023-11-21 12:56:30 浏览: 129
可以使用Python内置的socket库来启动服务,然后使用pickle库将函数序列化并发送到客户端,客户端再反序列化并调用该函数。具体步骤如下:
1. 在服务端定义一个函数,例如:
```python
def add(x, y):
return x + y
```
2. 使用socket库启动服务端,监听客户端的请求:
```python
import socket
import pickle
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8888))
server_socket.listen(1)
print('Server is listening...')
while True:
conn, addr = server_socket.accept()
print(f'Connected by {addr}')
data = conn.recv(1024)
if not data:
break
func_name, args = pickle.loads(data)
func = globals()[func_name]
result = func(*args)
conn.sendall(pickle.dumps(result))
conn.close()
```
3. 在客户端调用该函数:
```python
import socket
import pickle
def call_server():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8888))
func_name = 'add'
args = (1, 2)
data = pickle.dumps((func_name, args))
client_socket.sendall(data)
result = pickle.loads(client_socket.recv(1024))
print(result)
client_socket.close()
```
调用`call_server()`函数即可启动客户端并调用服务端的`add()`函数,输出结果为3。
阅读全文