func listenRequest(conn net.Conn) {
	defer func() {
		if x := recover(); x != nil {
			//common.PanicLog(x, string(debug.Stack()), "", "")
			log.Debug(fmt.Sprintf("%s %+v", debug.Stack(), x))
		}
	}()
	log.Debugf("[Handle] start handle charge connection from %s to %s \n", conn.RemoteAddr().String(), conn.LocalAddr().String())
	defer conn.Close()
	var gameId int
	for {
		gameId = 1
		bodyStr, err := snet.ClientRecvBody(gameId, conn)
		if err != nil {
			break
		}
		var rqBody snet.REQUEST
		json.Unmarshal([]byte(bodyStr), &rqBody)
		log.Debugf("Client request %+v", rqBody)
		rBody, disconnect := RequestHandle(gameId, rqBody)
		if disconnect {
			return
		}
		var rsBody snet.RESPONSE
		rsBody.Response = rqBody.Request
		rsBody.Data = rBody
		log.Debugf("Server response %+v", rsBody)
		rsBytes, err := json.Marshal(rsBody)
		if err != nil {
			break
		}
		snet.ClientSendBody(gameId, conn, string(rsBytes))
	}
}
func main() {
	Init()
	go socketChargeService()
	quitCode := <-Quit
	log.Debugf("Server quit by code[%d]", quitCode)
	Exit(quitCode)
}
//func postToServer:post request data(json) to the sdk's server,and get the []byte data later with no encode or decode
func PostToHTTPServer(targetUrl string, reqData []byte) (response []byte) {
	log.Debugf("start post data to ky sdk:time %s , url: %s\n", time.Now(), targetUrl)
	resp, err := http.Post(targetUrl, "application/json", bytes.NewBuffer(reqData)) // Todo
	log.Debugf("end post data to ky sdk:time %s , url: %s\n", time.Now(), targetUrl)

	if err != nil {
		panic(err.Error())
	}
	defer resp.Body.Close()

	resp_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err.Error())
	}
	log.Debugf("req_body:%x\n", reqData)
	log.Debugf("resp_body:%+v\n", string(resp_body))
	log.Debugf("resp_status:%s\n", resp.Status)
	return resp_body
}
func GetOrder(orderId int) (order model.Order, ok bool) {
	orderI, ok := cache.Get(getOrderKey(orderId))

	if !ok {

		rows, err := db.Query(SELECT_ORDER_BY_ID, orderId)
		if err != nil {
			panic(err.Error())
		}
		if rows.Next() {
			err = rows.Scan(&order.Id, &order.CoOrderId, &order.UserId, &order.PlayerId, &order.GameId, &order.ServerId, &order.Amount, &order.PayType, &order.ProductId, &order.ProductCount, &order.ExtData, &order.SdkType, &order.Source, &order.OrderTime, &order.PayTime, &order.OrderStatus, &order.PayStatus, &order.SdkInfo)
			if err != nil {
				panic(err.Error())
			}
		}
		defer rows.Close()
		cache.SetD(getOrderKey(order.Id), order)
		log.Debugf("Get order from db [%+v]", order)
	} else {
		order = orderI.(model.Order)
		log.Debugf("Get order from cache [%+v]", order)
	}
	return order, true
}
func GetToHTTPServer(targetUrl string, paramMap map[string]interface{}) (response []byte) {
	targetUrl += "?"
	for key, value := range paramMap {
		valueStr := fmt.Sprintf("%v", value)
		targetUrl += key + "=" + valueStr + "&"
	}
	targetUrl = targetUrl[:len(targetUrl)-1]
	log.Debugf("start get data from sdk:time %s , url: %s\n", time.Now(), targetUrl)
	resp, err := http.Get(targetUrl)
	log.Debugf("end get data from sdk:time %s , url: %s\n", time.Now(), targetUrl)

	if err != nil {
		panic(err.Error())
	}
	defer resp.Body.Close()

	resp_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err.Error())
	}
	log.Debugf("resp_body:%+v\n", string(resp_body))
	log.Debugf("resp_status:%s\n", resp.Status)
	return resp_body
}
Exemple #6
0
func payMsgHandler() {
	for {
		morder := <-payChan
		order, ok := dao.GetOrder(morder.Id)
		if !ok {
			log.Debugf("Pay chan got new message but order id is invalid [%+v]", morder)
			continue
		}
		//判定是否需要被保存
		dao.SaveOrder(order)
		//判定是否需要被通知
		//		if morder.PayStatus != order.PayStatus || morder.OrderStatus != order.OrderStatus {
		//			snet.NotifyOrderState(morder)
		//		}
		snet.NotifyOrderState(morder)
	}
}
func socketChargeService() {
	ln, err := net.Listen("tcp", fmt.Sprintf(":%d", content.MainListenPort))
	if err != nil {
		log.Debugf("listen on port %d failed %s \n", content.MainListenPort, err.Error())
		Quit <- 1
		return
	}

	log.Debug("Starting charge socket")
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Debug("Accept connection failed")
			continue
		}
		go listenRequest(conn)
	}
}
Exemple #8
0
func (s360 SDK360) ConfirmNotify(w http.ResponseWriter, dataBytes []byte) (rorder Order) {
	chargeMap := make(map[string]interface{})
	json.Unmarshal(dataBytes, &chargeMap)
	log.Debugf("charegeInfo : %+v\n", chargeMap)

	//数据包合法性验证
	coAppKey := chargeMap["app_key"].(string)
	coProductId := chargeMap["product_id"].(string)
	coAmount := chargeMap["amount"].(float64)
	coAppUid := chargeMap["app_uid"].(string)
	coAppExt1 := chargeMap["app_ext1"].(string)
	coAppExt2 := chargeMap["app_ext2"].(string)
	coUserId := int(chargeMap["user_id"].(float64))
	coOrderId := int(chargeMap["order_id"].(float64))
	coGatewayFlag := chargeMap["gateway_flag"].(string)
	coSignType := chargeMap["sign_type"].(string)
	coAppOrderId := chargeMap["app_order_id"].(string)
	//	coSignReturn := chargeMap["sign_return"].(string)
	coSign := chargeMap["sign"].(string)
	//需要排序参数md5
	paramMap := make(map[string]interface{})
	paramMap["app_key"] = coAppKey
	paramMap["product_id"] = coProductId
	paramMap["amount"] = coAmount
	paramMap["app_uid"] = coAppUid
	paramMap["app_ext1"] = coAppExt1
	paramMap["app_ext2"] = coAppExt2
	paramMap["user_id"] = coUserId
	paramMap["order_id"] = coOrderId
	paramMap["gateway_flag"] = coGatewayFlag
	paramMap["sign_type"] = coSignType
	paramMap["app_order_id"] = coAppOrderId

	if chargeMap["app_key"].(string) != s360.AppKey {
		log.Debug("[Error]got 360 charge notify but appid check failed")
		return
	}
	paramStr := utils.SortStringMapToUrlParam(paramMap)
	if !utils.MD5Check(coSign, paramStr) {
		log.Debug("[Error]got 360 charge notify but md5 check failed")
		return
	}
	return
}
Exemple #9
0
func (snet *SNetD) ClientSendBody(conn net.Conn, sendbody string) {

	buf := new(bytes.Buffer)
	w := gzip.NewWriter(buf)
	if _, err := w.Write([]byte(sendbody)); err != nil {
		panic(err.Error())
	}
	if err := w.Close(); err != nil {
		panic(err.Error())
	}
	body := string(buf.Bytes())

	log.Debugf("<<< sending %d->%d body:\n%s\n", len(sendbody), len(body), sendbody)

	var retHead HEADER
	retHead.ContentSize = uint32(len(sendbody))
	retHead.Sign = FRHEADERSIGN
	retHead.Version = 0x00000001
	retHead.Bodysize = uint32(len(body))

	retHeadBuf := bytes.NewBuffer(nil)
	binary.Write(retHeadBuf, binary.LittleEndian, &retHead)

	conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
	n, err := conn.Write(retHeadBuf.Bytes())
	if err != nil || n != len(retHeadBuf.Bytes()) {
		conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
		n, err := conn.Write(retHeadBuf.Bytes())
		if err != nil || n != len(retHeadBuf.Bytes()) {
			panic(err.Error())
		}
	}

	conn.SetWriteDeadline(time.Now().Add(30 * time.Second))
	n, err = conn.Write([]byte(body))
	if err != nil || n != len([]byte(body)) {
		conn.SetWriteDeadline(time.Now().Add(30 * time.Second))
		n, err := conn.Write([]byte(body))
		if err != nil || n != len([]byte(body)) {
			panic(err.Error())
		}
	}
}
Exemple #10
0
func (snet *SNetD) ClientRecvBody(conn net.Conn) (body string, err error) {
	var header HEADER
	packetbuf := make([]byte, 16)
	conn.SetReadDeadline(time.Now().Add(60 * time.Second))
	n, err := conn.Read(packetbuf)
	if err != nil {
		log.Debugf("read header error %s \n", err.Error())
		return
	}

	buf := bytes.NewBuffer(packetbuf[0:n])
	binary.Read(buf, binary.LittleEndian, &header)

	if header.Sign != FRHEADERSIGN {
		err = errors.New("header sign not match, disconnect")
		log.Debug("header sign not match, disconnect")
		return
	}

	bytesExpected := int(header.Bodysize)
	bodyBytes := make([]byte, 0)
	bytesRead := 0

	for bytesRead < bytesExpected {
		bytes := make([]byte, bytesExpected-bytesRead)

		conn.SetReadDeadline(time.Now().Add(5 * time.Second))
		n, err = conn.Read(bytes)
		//log.Debugf(">>>>>>>>>>>>>>>>>> %d %d <<<<<<<<<<<<<<<<<< |%s|", n, len(bytes[:n]), bytes[:n])
		if err != nil {
			log.Debugf("read body error %s \n", err.Error())
			return
		}
		bytesRead += n
		bodyBytes = append(bodyBytes, bytes[:n]...)
	}

	body = string(bodyBytes)

	{
		buf := new(bytes.Buffer)
		if _, e := buf.WriteString(body); e != nil {
			err = errors.New("received body gzip failed")
			log.Debug("received body gzip failed")
			return
		}

		r, e := gzip.NewReader(buf)
		if e != nil {
			err = errors.New("received body gzip failed")
			log.Debug("received body gzip failed")
			return
		}
		b, e := ioutil.ReadAll(r)
		if e != nil {
			err = errors.New("received body gzip failed")
			log.Debug("received body gzip failed")
			return
		}
		body = string(b)

		if e := r.Close(); e != nil {
			err = errors.New("received body gzip failed")
			log.Debug("received body gzip failed")
			return
		}
	}

	if header.ContentSize != uint32(len(body)) {
		err = errors.New("received body content size mismatch")
		log.Debug("received body content size mismatch")
		return
	}

	log.Debugf(">>> receiving %d->%d body:\n %s", header.ContentSize, header.Bodysize, body)
	return
}
Exemple #11
0
func notifyGameService(gameId int, serverId int, notifyBody []byte) {
	respbytes := PostToHTTPServer("localhost:2333", notifyBody)
	log.Debugf("Notify to localhost:2333 request [%+v],recv response [%+v]", notifyBody, respbytes)
}