Created
July 4, 2012 23:25
-
-
Save jiridanek/3050053 to your computer and use it in GitHub Desktop.
Blocking reads from buffered reader (Bufio)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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