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".
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.
Last updated