Lecture 09-Network Programming using Golang
Lecture 09-Network Programming using Golang
Lecture 09
Network Programming using Golang
Lecture 09 – Network Programming using Golang
package main
import (
"net“
//...
)
Lecture 09 – Network Programming using Golang
import (
"log"
"net"
)
func main() {
ln, err := net.Listen("tcp", ":6000")
if err != nil {
log.Fatal(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handleConnection(conn)
}
}
}
Lecture 09 – Network Programming using Golang
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "localhost:6000")
if err != nil {
// handle error
}
recvdSlice := make([]byte, 11)
conn.Read(recvdSlice)
fmt.Println(string(recvdSlice))
}
Lecture 09 – Network Programming using Golang
Goroutines
package main
import (
"fmt"
"time"
)
func main() {
go say("world")
say("hello")
}
Lecture 09 – Network Programming using Golang
Channels
package main
import "fmt"
func sendValues(myIntChannel chan int){
func main() {
myIntChannel := make(chan int)
Channels
package main
import "fmt"
func sendValues(myIntChannel chan int){
func main() {
myIntChannel := make(chan int)
go sendValues(myIntChannel)
Channels
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
Lecture 09 – Network Programming using Golang
Channels Usage
// Declare a channel
ch := make(chan int) // working channel
// or
var ch chan int // has to be initialized
// or
c := make(chan Type, n) // channel with buffer capacity n
// Add a value to a channel
ch <- 5 // arrow pointing to channel
// Retrieve a value from channel
value := <- ch // arrow pointing away from channel
// Close a channel
close(channel)
// Declare uni directional channels
r := make(<-chan int) // read only channel
w := make(chan<- int) // write only channel
Lecture 09 – Network Programming using Golang
Network Serialization
• How to send a block over the network to
other peers.
Network Serialization
• Alternatively, use gob package.
• Package gob manages streams of gobs -
binary values exchanged between an
Encoder (transmitter) and a Decoder
(receiver).
Lecture 09 – Network Programming using Golang
server.go
gobEncoder := gob.NewEncoder(c)
err := gobEncoder.Encode(block2)
if err != nil {
log.Println(err)
}
}
Lecture 09 – Network Programming using Golang
client.go
type Block struct {
Transaction string
PrevPointer *Block
}
func main() {
conn, err := net.Dial("tcp", "localhost:6000")
if err != nil {
//handle error
}
var recvdBlock Block
dec := gob.NewDecoder(conn)
err = dec.Decode(&recvdBlock)
if err != nil {
//handle error
}
fmt.Println(recvdBlock.Transaction)
fmt.Println(recvdBlock.PrevPointer.Transaction)
}
Lecture 09 – Network Programming using Golang