Socket

Sockets in Go

Here's a simple socket connexion between a client and a server.

Go provides a powerful library for network programming, including support for creating and using sockets.

What is a socket?

A socket is a low-level data communication endpoint that enables communication between processes on the same or different devices.

Server

This is a simple TCP server in Go programming language. The code starts a server on localhost at port 54321. The server listens for incoming connections from clients. When a client connects, the server accepts the connection and launches a new goroutine to handle the request. In the processClient function, the server reads the incoming data from the client and sends back a response to the client with the message "Thanks! got your message".

package main

import (
        "fmt"
        "net"
        "os"
)

const (
        SERVER_HOST = "localhost"
        SERVER_PORT = "54321"
        SERVER_TYPE = "tcp"
)

func main() {
        fmt.Println("Server Running...")
        server, err := net.Listen(SERVER_TYPE, SERVER_HOST+":"+SERVER_PORT)
        if err != nil {
                fmt.Println("Error listening:", err.Error())
                os.Exit(1)
        }
        defer server.Close()
        fmt.Println("Listening on " + SERVER_HOST + ":" + SERVER_PORT)
        fmt.Println("Waiting for client...")
        for {
                connection, err := server.Accept()
                if err != nil {
                        fmt.Println("Error accepting: ", err.Error())
                        os.Exit(1)
                }
                fmt.Println("client connected")
                go processClient(connection)
        }
}

func processClient(connection net.Conn) {
        buffer := make([]byte, 1024)
        mLen, err := connection.Read(buffer)
        if err != nil {
                fmt.Println("Error reading:", err.Error())
        }
        fmt.Println("Received: ", string(buffer[:mLen]))
        _, err = connection.Write([]byte("\nThanks!\nGot your message : " + string(buffer[:mLen])))
        connection.Close()
}

Client

This code is a Go program that implements a client that connects to a server using the TCP protocol and sends a message to the server. The code starts by importing the fmt and net packages, which are used to handle formatted output and network communication, respectively.

Constants are then defined for the server host, port, and type. In this case, the host is set to localhost, the port is 54321, and the type is set to tcp, which stands for Transmission Control Protocol.

The main function starts by calling the net.Dial function, which creates a new socket and connects to the server at the specified host and port. If there is an error, the program will panic.

Next, the code uses the connection.Write function to send a message to the server in the form of a byte array. Then, the code uses the connection.Read function to read the response from the server. The buffer variable is used to store the response, and mLen is the length of the message.

Finally, the connection is closed using the defer statement, which means that the connection will be closed when the function returns.

package main

import (
        "fmt"
        "net"
)

const (
        SERVER_HOST = "localhost"
        SERVER_PORT = "54321"
        SERVER_TYPE = "tcp"
)

func main() {
        //establish connection
        connection, err := net.Dial(SERVER_TYPE, SERVER_HOST+":"+SERVER_PORT)
        if err != nil {
                panic(err)
        }
        ///send some data
        _, err = connection.Write([]byte("Hello Server! Greetings."))
        buffer := make([]byte, 1024)
        mLen, err := connection.Read(buffer)
        if err != nil {
                fmt.Println("Error reading:", err.Error())
        }
        fmt.Println("Received: ", string(buffer[:mLen]))
        defer connection.Close()
}

Last updated