Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

Accept Connection on Socket

See more Socket/SSL/TLS Examples

Demonstrates how to create a TCP/IP socket, listen on a port, accept an incoming connection, and send a "Hello World" message to the client.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const listen_socket = try chilkat.Socket.init();
    defer listen_socket.deinit();

    // Bind to a port and listen for incoming connections:
    // This example will listen at port 5555 and allows for a backlog
    // of 25 pending connection requests.
    listen_socket.bindAndListen(5555, 25) catch {
        std.debug.print("{s}\n", .{try listen_socket.getLastErrorText(alloc)});
        return;
    };

    // Get the next incoming connection
    // Wait a maximum of 20 seconds (20000 millisec)
    const connected_socket = try chilkat.Socket.init();
    defer connected_socket.deinit();
    listen_socket.acceptNext(20000, connected_socket) catch {
        std.debug.print("{s}\n", .{try listen_socket.getLastErrorText(alloc)});
        return;
    };

    // Set maximum timeouts for reading an writing (in millisec)
    connected_socket.setMaxReadIdleMs(10000);
    connected_socket.setMaxSendIdleMs(10000);

    // Send a "Hello World!" message to the client:
    connected_socket.sendString("Hello World!") catch {
        std.debug.print("{s}\n", .{try connected_socket.getLastErrorText(alloc)});
        return;
    };

    // Close the connection with the client.
    // Wait a max of 20 seconds (20000 millsec)
    try connected_socket.close(20000);

    std.debug.print("success!\n", .{});
}