tcpServer.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package TcpServerLib
  2. import (
  3. "github.com/davecgh/go-spew/spew"
  4. "log"
  5. "net"
  6. "runtime"
  7. )
  8. // TCP server
  9. type server struct {
  10. address string // Address to open connection: localhost:9999
  11. onNewClientCallback func(c *Session)
  12. onClientConnectionClosed func(c *Session, closeCase int)
  13. onNewMessage func(c *Session, packetData []byte)
  14. }
  15. // Called right after server starts listening new client
  16. func (s *server) OnNewClient(callback func(c *Session)) {
  17. s.onNewClientCallback = callback
  18. }
  19. // Called right after connection closed
  20. func (s *server) OnClientConnectionClosed(callback func(c *Session, closeCase int)) {
  21. s.onClientConnectionClosed = callback
  22. }
  23. // Called when Session receives new message
  24. func (s *server) OnNewMessage(callback func(c *Session, packetData []byte)) {
  25. s.onNewMessage = callback
  26. }
  27. // Creates new tcp server instance
  28. func NewServer(address string) *server {
  29. log.Println("Creating server with address", address)
  30. server := &server{
  31. address: address,
  32. }
  33. server.OnNewClient(func(c *Session) {})
  34. server.OnNewMessage(func(c *Session, packetData []byte) {})
  35. server.OnClientConnectionClosed(func(c *Session, closeCase int) {})
  36. return server
  37. }
  38. // Start network server
  39. func (s *server) Listen() {
  40. listener, err := net.Listen("tcp", s.address)
  41. if err != nil {
  42. log.Fatal("Error starting TCP server.")
  43. }
  44. defer listener.Close()
  45. for {
  46. conn, _ := listener.Accept()
  47. client := &Session{
  48. conn: conn,
  49. Server: s,
  50. }
  51. go client.handleTcpRead()
  52. }
  53. }
  54. // 출처: https://github.com/gonet2/agent
  55. func PrintPanicStack(extras ...interface{}) {
  56. if x := recover(); x != any(nil) {
  57. log.Printf("%v", x)
  58. i := 0
  59. funcName, file, line, ok := runtime.Caller(i)
  60. for ok {
  61. log.Printf("PrintPanicStack. [func]: %s, [file]: %s, [line]: %d\n", runtime.FuncForPC(funcName).Name(), file, line)
  62. i++
  63. funcName, file, line, ok = runtime.Caller(i)
  64. }
  65. for k := range extras {
  66. log.Printf("EXRAS#%v DATA:%v\n", k, spew.Sdump(extras[k]))
  67. }
  68. }
  69. }