码迷,mamicode.com
首页 > Web开发 > 详细

golang net package simulation

时间:2015-03-21 15:25:51      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Let‘s make some fun to simulation  Server - Client.

 

1.  socket

I implement a echo server and use telnet to simulate the socket client.

in this way,  we don‘t need to implement our socket client but can test our client server in a standard way.

技术分享

It can support multiple telnet clients concurrently. The behavior is as bellow.

技术分享

when user input "BYE",  the connect to server shuts down.

code snippet:

 1 package main
 2 
 3 import (
 4     "bufio"
 5     "fmt"
 6     "io"
 7     "log"
 8     "net"
 9     "strings"
10 )
11 
12 func main() {
13     // Listen on TCP port 2000 on all interfaces.
14     l, err := net.Listen("tcp", ":2000")
15     if err != nil {
16         log.Fatal(err)
17     }
18     defer l.Close()
19 
20     for {
21         // Wait for a connection.
22         conn, err := l.Accept()
23         if err != nil {
24             log.Fatal(err)
25         }
26         fmt.Println("INFO: accept a client")
27 
28         // Handle the connection in a new goroutine.
29         go func(c net.Conn) {
30             defer c.Close()
31 
32             rd := bufio.NewReader(c)
33             for {
34                 line, _, err := rd.ReadLine()
35                 if err != nil && err != io.EOF {
36                     log.Fatal(err)
37                 }
38 
39                 s := string(line)
40                 fmt.Println("LOG:", s)
41 
42                 //since rd.ReadLine() has trimed last "\n", append here to echo
43                 _, err = conn.Write([]byte("ECHO:" + s + "\r\n"))
44                 if err != nil {
45                     log.Fatal(err)
46                 }
47 
48                 if strings.ToLower(s) == "bye" {
49                     fmt.Println("INFO: client closed")
50                     break
51                 }
52             }
53         }(conn)
54     }
55 }

 

2. http.Client

golang net package simulation

标签:

原文地址:http://www.cnblogs.com/harrysun/p/4355523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!