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.

Related course:
Learn How To Code: Google’s Go (golang) Programming Language

Socket client golang

Introduction

To use network sockets, load the net module. The net module lets you make network connections and transmit data.

1
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

1
2
// connect to server
conn, _ := net.Dial("tcp", "127.0.0.1:8000")

Send and receive data with:

1
2
3
4
// 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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 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)
}
}