protoevent
v1.0.0 Release
ProtoEvent 是 Golang 中基于事件的 TCP 连接处理库。它很简单,并且没有过多利用建立新协议连接的基本功能。 ProtoEvent 重新实现了net.Listener
和net.Conn
接口,以扩展捕获网络通信中发生的各种事件的能力。
当您必须照顾组织不好的简单网络应用程序代码库并最终生成更多意大利面条代码时,这已经够痛苦的了。至少,我们现在能够根据某个网络事件来组织应用程序逻辑。
go get -u https://github.com/parinpan/protoevent
服务器端应用程序:
package main
import (
"encoding/json"
"fmt"
"net"
"github.com/parinpan/protoevent"
)
type Message struct {
From string `json:"from"`
}
func main () {
servant , event , err := protoevent . CreateServant ( "tcp" , "0.0.0.0:8089" )
if nil != err {
panic ( err )
}
event . OnConnectionError ( func ( err error ) {
})
event . OnConnectionAccepted ( func ( conn net. Conn ) {
fmt . Println ( "Accepting new connection: " , conn . RemoteAddr ())
})
event . OnConnectionClosed ( func ( conn net. Conn ) {
})
event . OnReceiveMessageError ( func ( conn net. Conn , err error ) {
})
event . OnMessageReceived ( func ( conn net. Conn , message [] byte , rawMessage [] byte ) {
fmt . Println ( "Received a message: " , string ( message ))
var msg Message
_ = json . Unmarshal ( message , & msg )
// send a message back to client
sayHiMessage := fmt . Sprint ( "Hi " , msg . From , ". Welcome to ProtoEvent!" )
conn . Write ([] byte ( sayHiMessage ))
})
event . OnSendMessageError ( func ( conn net. Conn , message [] byte , err error ) {
})
event . OnMessageSent ( func ( conn net. Conn , message [] byte ) {
fmt . Println ( "Sent a message: " , string ( message ))
})
servant . SetDefaultReadSize ( 4096 ) // set default read size per chunk in bytes
servant . Serve ()
}
客户端应用程序:
package main
import (
"fmt"
"net"
"github.com/parinpan/protoevent"
)
func main () {
agent , event := protoevent . CreateAgent ( "tcp" , "0.0.0.0:8089" )
agent . SetDefaultReadSize ( 4096 ) // set default read size per chunk in bytes
event . OnConnectionError ( func ( err error ) {
})
event . OnConnectionAccepted ( func ( conn net. Conn ) {
fmt . Println ( "Accepting new connection: " , conn . RemoteAddr ())
})
event . OnConnectionClosed ( func ( conn net. Conn ) {
})
event . OnReceiveMessageError ( func ( conn net. Conn , err error ) {
})
event . OnMessageReceived ( func ( conn net. Conn , message [] byte , rawMessage [] byte ) {
fmt . Println ( "Received a message: " , string ( message ))
})
event . OnSendMessageError ( func ( conn net. Conn , message [] byte , err error ) {
})
event . OnMessageSent ( func ( conn net. Conn , message [] byte ) {
fmt . Println ( "Sent a message: " , string ( message ))
})
// trigger a message to get connected with the server at first
err := agent . Run ( func ( conn net. Conn ) error {
_ , err := conn . Write ([] byte ( `{"from": "AgentV1"}` ))
return err
})
if nil != err {
panic ( err )
}
}
如果您有任何疑问。您可以通过以下方式联系我: