feat: 对接Python,暴露接口

This commit is contained in:
2026-03-30 22:48:36 +08:00
parent 24467c04c0
commit d678bfc326
22 changed files with 1311 additions and 51 deletions

View File

@@ -63,6 +63,36 @@ static kcp_peer_entry_t *kcp_hub_find_peer(kcp_hub_t *hub, const char *peer_id)
return NULL;
}
static int kcp_hub_peer_id_has_suffix(const char *peer_id, const char *suffix) {
size_t peer_len;
size_t suffix_len;
if (peer_id == NULL || suffix == NULL) {
return 0;
}
peer_len = strlen(peer_id);
suffix_len = strlen(suffix);
return peer_len >= suffix_len && strcmp(peer_id + peer_len - suffix_len, suffix) == 0;
}
static int kcp_hub_configure_peer_transport(kcp_conn_t *conn, const char *peer_id) {
kcp_conn_options_t options;
if (conn == NULL || peer_id == NULL) {
errno = EINVAL;
return -1;
}
if (kcp_hub_peer_id_has_suffix(peer_id, "-ctrl")) {
kcp_conn_options_set_control_defaults(&options);
return kcp_conn_apply_options(conn, &options);
}
if (kcp_hub_peer_id_has_suffix(peer_id, "-video")) {
kcp_conn_options_set_video_defaults(&options);
return kcp_conn_apply_options(conn, &options);
}
return 0;
}
static int kcp_hub_send_server_error(kcp_conn_t *conn, const char *to, const char *message) {
message_t msg;
protocol_message_init(&msg);
@@ -255,6 +285,7 @@ static int kcp_hub_handle_peer_message(kcp_hub_t *hub, const char *peer_id, kcp_
switch (msg->type) {
case MSG_TYPE_TEXT:
case MSG_TYPE_FILE:
case MSG_TYPE_BINARY:
snprintf(msg->from, sizeof(msg->from), "%s", peer_id);
if (kcp_hub_deliver_to_local_peer(hub, msg) == 0) {
return 0;
@@ -294,7 +325,7 @@ static int kcp_hub_handle_peer_message(kcp_hub_t *hub, const char *peer_id, kcp_
return 0;
case MSG_TYPE_REGISTER:
case MSG_TYPE_ERROR:
if (kcp_hub_send_server_error(conn, peer_id, "registered peers can only send text or file messages") != 0) {
if (kcp_hub_send_server_error(conn, peer_id, "registered peers can only send text, file, or binary messages") != 0) {
return -1;
}
errno = EPROTO;
@@ -358,6 +389,11 @@ static int kcp_hub_register_conn(kcp_hub_t *hub, kcp_conn_t *conn, char *peer_id
pthread_rwlock_unlock(&hub->lock);
snprintf(peer_id, peer_id_len, "%s", msg.from);
if (kcp_hub_configure_peer_transport(conn, peer_id) != 0) {
kcp_hub_unregister(hub, peer_id, conn);
protocol_message_clear(&msg);
return -1;
}
protocol_message_clear(&msg);
return 0;
}
@@ -518,7 +554,7 @@ int kcp_hub_serve_relay(kcp_hub_t *hub) {
protocol_message_clear(&msg);
continue;
}
if (msg.type != MSG_TYPE_TEXT && msg.type != MSG_TYPE_FILE && msg.type != MSG_TYPE_ERROR) {
if (msg.type != MSG_TYPE_TEXT && msg.type != MSG_TYPE_FILE && msg.type != MSG_TYPE_BINARY && msg.type != MSG_TYPE_ERROR) {
protocol_message_clear(&msg);
continue;
}