Skip to content

Instantly share code, notes, and snippets.

@jiridanek
Created July 4, 2012 23:25
Show Gist options
  • Save jiridanek/3050053 to your computer and use it in GitHub Desktop.
Save jiridanek/3050053 to your computer and use it in GitHub Desktop.
Blocking reads from buffered reader (Bufio)
package main
import (
"fmt"
"net"
"bufio"
)
func main() {
conn, err := net.Dial("tcp", ":8822")
if err != nil {
fmt.Println("client: cannot connect:", err)
return
}
bufreader := bufio.NewReader(conn)
switch "Read" {
case "ReadString":
// read two lines
for i := 0; i < 2; i++ {
// keep trying until prevailed
for {
line, err := bufreader.ReadString('\n')
if err != nil {
fmt.Println("client: ReadString failed:", err)
continue
}
fmt.Println("client: got a line:", line)
break
}
}
case "Read":
chunk := make([]byte, 255)
for i := 0; i < 2; i++ {
// keep trying until prevailed
for {
n, err := bufreader.Read(chunk)
if err != nil {
fmt.Println("client: Read failed:", err)
continue
}
fmt.Println("client: got a chunk:", n, ":", string(chunk))
break
}
}
}
}
package main
import (
"fmt"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8822")
if err != nil {
fmt.Println("server: cannot start:", err)
return
}
for {
conn, err := ln.Accept()
if err != nil {
// handle error
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
conn.Write([]byte("Pršelo, jen se lilo\n"))
time.Sleep(3*time.Second)
// conn.Close()
conn.Write([]byte("a tele doma nebylo.\n"))
conn.Write([]byte("Jela Anička na kole,\n"))
conn.Write([]byte("… bye\n"))
err := conn.Close()
if err != nil {
fmt.Println("server: dirty end:", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment