Example #1
0
func StartServer() {
	iniConf := common.Config()
	ip := iniConf.DefaultString("tcp_ip", "10.0.2.15")
	port := iniConf.DefaultString("tcp_port", "8888")
	g_IP = util.IPToInt(ip)
	g_Port = uint32(util.Atoi(port))

	listener, err := common.TCPServer(ip + ":" + port)
	if err != nil {
		panic(err)
	}
	/*
		udp_addr1 := iniConf.DefaultString("udp_address1", "127.0.0.1:9100")
		udp_addr2 := iniConf.DefaultString("udp_address2", "127.0.0.1:9101")

		udpSocket1, err := common.UDPServer(udp_addr1)
		if err != nil {
			panic(err)
		}
		udpSocket2, err := common.UDPServer(udp_addr2)
		if err != nil {
			panic(err)
		}
	*/
	service := &Service{
		Listener:  listener,
		ClientCh:  make(chan *Client, 1000),
		WaitGroup: sync_.NewWaitGroup(),
		ClientMap: make(map[uint32]*Client),
		RWMutex:   &sync.RWMutex{},
	}
	for i := 0; i < CLIENT_GROUP_NUM; i++ {
		NewClientGroup(service)
	}
	go service.Serve()
	//go service.P2pService(udpSocket1)
	//go service.P2pService(udpSocket2)

	topic := fmt.Sprintf("conn_%v_%v", ip, port)
	if _, err := common.NsqConsumerGO(topic, "conn-channel", 3, service); err != nil {
		panic(err)
	}
	// Handle SIGINT and SIGTERM.
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
	syslog.Info("recv signal and exit:", <-ch)
	service.Stop()
	return
}
Example #2
0
func (this *Service) P2pService(sock *net.UDPConn) {
	this.WaitGroup.AddOne()
	defer this.WaitGroup.Done()
	exitNotify := this.WaitGroup.ExitNotify()
	var buf [2048]byte
	for {
		select {
		case <-exitNotify:
			return
		default:
		}
		sock.SetDeadline(time.Now().Add(NET_READ_MAX_DATELINE))
		n, addr, err := sock.ReadFromUDP(buf[:])
		if err != nil {
			syslog.Info(err)
			continue
		}
		if n < 4 {
			syslog.Info("udp data package too small")
			continue
		}
		sid := binary.BigEndian.Uint32(buf[:4])
		this.RWMutex.RLock()
		client, ok := this.ClientMap[sid]
		this.RWMutex.RUnlock()
		if ok == false {
			syslog.Debug("client not exist!!! sid:", sid)
			continue
		}
		client.IP = util.IPToInt(addr.String())
		client.Port = uint32(addr.Port)
		if _, err := sock.WriteToUDP([]byte(addr.String()), addr); err != nil {
			syslog.Info("udp send data failed!!!", err)
			continue
		}
	}
}