how to set up a zig tcp server socket

142 Views Asked by At

I am learning zig and want to make a simple tcp server. have a general idea on how to do this in C. My understanding on what needs to happen is this:

  1. get a File Descriptor

  2. Set the options for how you want the socket to be connected.

  3. Bind the File Descriptor to a socket. Setting the options for that socket (TCP, UDP, etc..)

  4. Use the socket

  5. Close the socket.

I Have tried looking for examples online, but most of them are too abstracted or they are HTTP protocols (which I don't want).

It seems that every one of my attempts results in a client socket rather than a server. This is my example

const std = @import("std");
const print = std.debug.print;
const net = std.net;

pub fn main() void {

    print("Starting IP-Addres vendor\n", .{});
    const addr = net.Address.resolveIp("127.0.0.1", 9090) catch | err | {
        print("An error occured while resolving the IP address: {}\n", .{err});
        return; 
    };
    
    // I was hoping this would yield a server socket, but it seems to be a client
    // socket. This is where my program ends. 
    const socket = net.tcpConnectToAddress(addr) catch | err | {
        print("An error occured creating a TCP connection: {}\n", .{err});
        return; 
    };
    
    defer socket.close();

    var server = net.Server{.listen_address=addr, .stream=socket};
    print("Starting TCP server...\n", .{});    
    
    while ( net.Server.accept(&server)) | conn | {        
        print("Received a connection\n",.{} );
        conn.stream.close();
        
    } else  |err| {        
        print("An error occured while acception a connection: {}\n", .{err});
        
    }
}

My end goal is to have this server communicate to a client i wrote in C. The whole thing is a learning experience, that is why the mix of languages.

Thanks in advance.

I expected the socket to be a server socket that can receive connections and communicate with clients over a custom protocol. The error I get is the following:

An error occured creating a TCP connection: error.ConnectionRefused

I don't have any other processes running on that port, which tells me that the socket I tried to open was a client attempt.

zig version 0.12.0-dev.2990+31763d28c

0

There are 0 best solutions below