golang net package simulation

harrysun · · 2512 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:harrysun

查看原文:golang net package simulation

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2512 次点击  
加入收藏 微博
2 回复  |  直到 2000-01-01 00:00:00
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传