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 )
}
}
如果您有任何疑問。您可以透過以下方式聯絡我: