Created
April 10, 2023 02:00
-
-
Save kalsprite/06d65f3b0945289ebb762e55affe1734 to your computer and use it in GitHub Desktop.
Basic TCP Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import "core:fmt" | |
| import "core:net" | |
| import "core:os" | |
| import "core:strings" | |
| import "core:strconv" | |
| main :: proc() { | |
| ep, epok := net.parse_endpoint("127.0.0.1:3000") | |
| assert(epok) | |
| sock, serr := net.listen_tcp(ep, 5) | |
| fmt.println(serr) | |
| defer net.close(sock) | |
| fmt.println("Server started on 127.0.0.1:3000") | |
| for { | |
| client, _, aerr := net.accept_tcp(sock) | |
| if aerr != nil { | |
| fmt.println("Error accepting connection:", aerr) | |
| break | |
| // continue | |
| } | |
| handle_client(client) | |
| } | |
| } | |
| handle_client :: proc(client: net.TCP_Socket) { | |
| defer net.close(client) | |
| using strings | |
| // Read request | |
| buffer: [4096]byte | |
| n_read, rerr := net.recv_tcp(client, buffer[:]) | |
| if rerr != nil { | |
| fmt.println("Error reading request:", rerr) | |
| return | |
| } | |
| fmt.println("request:", string(buffer[:n_read])) | |
| // Define your JSON response | |
| json_data := `{"status": "success","message": "Hello, Network!"}` | |
| itoa_len: [16]u8 | |
| js_len := strconv.itoa(itoa_len[:], len(json_data)) | |
| sb := builder_make(context.temp_allocator) | |
| write_string(&sb, "HTTP/1.1 200 OK\r\n") | |
| write_string(&sb, "Content-Type: application/json\r\n") | |
| write_string(&sb, "Content-Length: ") | |
| write_string(&sb, js_len) | |
| write_string(&sb, "\r\n\r\n") | |
| write_string(&sb, json_data) | |
| str := to_string(sb) | |
| // Write the response | |
| n_written, werr := net.send_tcp(client, transmute([]u8)str) | |
| if werr != nil { | |
| fmt.println("Error writing response:", werr) | |
| return | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment