0% found this document useful (0 votes)
37 views2 pages

Socket Server Golang

The document provides an introduction to setting up a socket server using Go programming language. It outlines the basic steps required to listen on a network port, accept connections, and process incoming data in a loop. An example code snippet demonstrates how to create a simple socket server that listens on port 8000 and receives messages from clients.

Uploaded by

jack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views2 pages

Socket Server Golang

The document provides an introduction to setting up a socket server using Go programming language. It outlines the basic steps required to listen on a network port, accept connections, and process incoming data in a loop. An example code snippet demonstrates how to create a simple socket server that listens on port 8000 and receives messages from clients.

Uploaded by

jack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Learn Go Programming Home Exercises

Network applications use sockets. Sockets is the raw network layer (TCP/UDP). Data is often
transmitted using protocols, but sockets let you define your own protocols.

This example uses golang to setup a socket server.

Socket server golang

introduction

To use sockets, load the net module, with the line import "net" . Then the steps are

sequentially to listen on a network port, to accept an incoming connections and then to process
incoming data in a loop.

...
// listen on port 8000
ln, _ := net.Listen("tcp", ":8000")

// accept connection
conn, _ := ln.Accept()

// run loop forever (or until ctrl-c)


for {
// process data
}

socket server example

The example below opens a socket server on port 8000 of your local computer. If you name the
program server.go , you can start it with go run server.go .

You can connect to the server with telnet, telnet 127.0.0.1 8000 or from another

computer in your local network. Then send any message, the server will receive them.

(make sure your firewall isn’t blocking).


// Very basic socket server
// https://golangr.com/

package main

import "net"
import "fmt"
import "bufio"

func main() {
fmt.Println("Start server...")

// listen on port 8000


ln, _ := net.Listen("tcp", ":8000")

// accept connection
conn, _ := ln.Accept()

// run loop forever (or until ctrl-c)


for {
// get message, output
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message Received:", string(message))
}
}

Cookie policy - Privacy policy - Terms of use


© 2021 golangr.com

You might also like