以下是使用open62541库在C语言中实现多个client连接一个server的代码示例:

#include <stdio.h>
#include <stdlib.h>
#include "open62541.h"

#define N_CLIENTS 10

UA_Boolean running = true;

// callback function for handling subscription notifications
static void dataChangeHandler(UA_Client *client, UA_UInt32 subId, void *subContext,
                              UA_UInt32 monId, void *monContext, UA_DataValue *value) {
    UA_String *data = (UA_String*)value->value.data;
    printf("Received data: %.*s\n", (int)data->length, data->data);
}

// function to create a new client and connect to the server
UA_Client *createClient() {
    UA_ClientConfig *config = UA_ClientConfig_new_default();
    UA_Client *client = UA_Client_new(config);
    UA_ClientConfig_delete(config);
    UA_StatusCode status = UA_Client_connect(client, "opc.tcp://localhost:4840");
    if(status != UA_STATUSCODE_GOOD) {
        printf("Failed to connect to server. Error code: %i\n", status);
        UA_Client_delete(client);
        return NULL;
    }
    printf("Client connected to server.\n");
    return client;
}

// main function
int main(void) {
    UA_Client *clients[N_CLIENTS];

    // create and connect multiple clients
    for(int i = 0; i < N_CLIENTS; i++) {
        clients[i] = createClient();
        if(!clients[i]) {
            return EXIT_FAILURE;
        }
    }

    // create a subscription for each client
    for(int i = 0; i < N_CLIENTS; i++) {
        UA_Subscription *subscription = UA_Subscription_new(UA_SubscriptionSettings_default, dataChangeHandler, NULL, NULL);
        UA_Client_Subscriptions_new(clients[i], subscription);
        UA_Subscription_addMonitoredItem(subscription, UA_NODEID_STRING(1, "test"), UA_ATTRIBUTEID_VALUE, NULL, NULL, NULL, NULL);
        printf("Client %i subscribed to node 'test'\n", i);
    }

    // wait for user input to exit
    printf("Press enter to exit...\n");
    getchar();

    // cleanup
    for(int i = 0; i < N_CLIENTS; i++) {
        UA_Client_delete(clients[i]);
    }
    return EXIT_SUCCESS;
}

该示例创建了10个client连接到同一个server,并为每个client创建了一个订阅。每个订阅将监视名为“test”的节点,并在数据发生改变时调用回调函数dataChangeHandler。在程序运行期间,用户可以随时按下回车键来退出程序。程序退出时,会清理所有已创建的client。

注意:在实际应用程序中,需要根据实际情况进行修改和调整。例如,需要根据实际的节点ID和属性ID来订阅节点,或者需要添加错误处理代码来处理连接失败等情况

open62541多个client连接一个server将client分别维护起来代码

原文地址: https://www.cveoy.top/t/topic/g7w8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录