-
Notifications
You must be signed in to change notification settings - Fork 205
/
tcp_server.go
86 lines (79 loc) · 2.35 KB
/
tcp_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* rpc/tcp_server.go *
* *
* hprose tcp server for Go. *
* *
* LastModified: Nov 1, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
package rpc
import (
"net"
"net/url"
)
// TCPServer is a hprose tcp server
type TCPServer struct {
TCPService
starter
uri string
listener *net.TCPListener
}
// NewTCPServer is the constructor for TCPServer
func NewTCPServer(uri string) (server *TCPServer) {
if uri == "" {
uri = "tcp://127.0.0.1:0"
}
server = new(TCPServer)
server.initTCPService()
server.starter.server = server
server.uri = uri
return
}
// URI return the real address of this server
func (server *TCPServer) URI() string {
if server.listener == nil {
panic(ErrServerIsNotStarted)
}
u, err := url.Parse(server.uri)
if err != nil {
panic(err)
}
return u.Scheme + "://" + server.listener.Addr().String()
}
// Handle the hprose tcp server
func (server *TCPServer) Handle() (err error) {
if server.listener != nil {
return ErrServerIsAlreadyStarted
}
u, err := url.Parse(server.uri)
if err != nil {
return err
}
addr, err := net.ResolveTCPAddr(u.Scheme, u.Host)
if err != nil {
return err
}
if server.listener, err = net.ListenTCP(u.Scheme, addr); err != nil {
return err
}
go server.ServeTCP(server.listener)
return nil
}
// Close the hprose tcp server
func (server *TCPServer) Close() {
if server.listener != nil {
listener := server.listener
server.listener = nil
listener.Close()
}
}