go socket simple

1. socket_server.go

 1 package main
 2 
 3 import (
 4     "net"
 5 
 6     "facework.im/share/logging"
 7 )
 8 
 9 func main() {
10     listen, err := net.Listen("tcp", "localhost:1024")
11     if err != nil {
12         logging.Error("Net Listen | %v", err)
13         return
14     }
15     defer listen.Close()
16 
17     logging.Debug("Waiting For Clients To Connection...")
18 
19     for {
20         conn, err := listen.Accept()
21         if err != nil {
22             logging.Debug("Liston Accept | %v", err)
23             continue
24         }
25 
26         logging.Notice("%v Tcp Connect Success.", conn.RemoteAddr().String())
27 
28         handleConnection(conn)
29     }
30 }
31 
32 // 处理连接
33 func handleConnection(conn net.Conn) {
34     buf := make([]byte, 2048)
35 
36     for {
37         n, err := conn.Read(buf)
38         if err != nil {
39             return
40         }
41 
42         logging.Debug("%v Receive Data: %v", conn.RemoteAddr().String(), string(buf[:n]))
43     }
44 }
View Code

2. socket_client.go

 1 package main
 2 
 3 import (
 4     "bufio"
 5     "net"
 6     "os"
 7 
 8     "facework.im/share/logging"
 9 )
10 
11 func main() {
12     server := "127.0.0.1:1024"
13     addr, err := net.ResolveTCPAddr("tcp4", server)
14     if err != nil {
15         logging.Error("Net ResolveTCPAddr | %v", err)
16         return
17     }
18 
19     conn, err := net.DialTCP("tcp", nil, addr)
20     if err != nil {
21         logging.Error("Net DialTCP | %v", err)
22         return
23     }
24 
25     logging.Notice("Connect To Server Success.")
26 
27     sender(conn)
28 }
29 
30 // 发送消息
31 func sender(conn net.Conn) {
32     msgin := bufio.NewReader(os.Stdin)
33     for {
34         line, _, _ := msgin.ReadLine()
35         msg := string(line)
36         conn.Write([]byte(msg))
37     }
38 }
View Code

3. 运行效果

posted @ 2017-09-15 10:51  hezhixiong  阅读(194)  评论(0编辑  收藏  举报