Socket client in golang (TCP). Sockets is the raw network layer (TCP/UDP). Data is often transmitted using protocols, but sockets let you define your own protocols.
This example creates a socket client. A socket server needs to be running.
Socket client golang
Introduction
To use network sockets, load the net module. The net module lets you make network connections and transmit data.
import "net"
A socket client does not specify a protocol, you can create your own protocol implementation if you want.
Sockets just let you send raw data from client to server and back.
Connects to the server with
// connect to server
conn, _ := net.Dial("tcp", "127.0.0.1:8000")
Send and receive data with:
// send to server
fmt.Fprintf(conn, text + "\n")
// wait for reply
message, _ := bufio.NewReader(conn).ReadString('\n')
Socket client example
This example connects to a network server. In this case, a socket server running ony your local computer.
In this example, the client connects to the server on port 8000, then sends a message the user tells and finally waits for a message.
(make sure your firewall isn’t blocking).
// socket client for golang
// https://golangr.com
package main
import "net"
import "fmt"
import "bufio"
import "os"
func main() {
// connect to server
conn, _ := net.Dial("tcp", "127.0.0.1:8000")
for {
// what to send?
reader := bufio.NewReader(os.Stdin)
fmt.Print("Text to send: ")
text, _ := reader.ReadString('\n')
// send to server
fmt.Fprintf(conn, text + "\n")
// wait for reply
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message from server: "+message)
}
}