public void MsgPacket(MsgPacket packet)
        {
            ScriptManager.Instance.Data[0] = packet.Message;
            ScriptManager.Instance.Data[1] = packet.Type;

            ScriptManager.Instance.AddEvent(ScriptManager.Instance.Target, ScriptManager.Instance.EventName, new Event(EventType.SendMsg, ScriptManager.Instance.Data, textData: packet.Message));
        }
Exemplo n.º 2
0
	private void SendClientSnapshot(ClientNode client){
		byte[] msg_buf = new byte[CConstVar.MAX_MSG_LEN];

		//构建snapshot
		BuildClientSnapshot(client);

		//机器人有自己的构建方法,不需要发送
		if(client.gEntity != null && (client.gEntity.r.svFlags & SVFlags.BOT) != SVFlags.NONE){
			return;
		}


		//这里要默认开始压缩
		MsgPacket msg = new MsgPacket();
		msg.Oob = false;
		msg.AllowOverflow = true;

		//让客户端知道服务器已经收到的可靠消息。
		msg.WriteInt(client.lastClientCommand);

		//发送任何可靠的服务器指令
		UpdateServerCommandsToClient(client, msg);

		//发送所有的相应的entityState和playerState
		WriteSnapshotToClient(client, msg);

		if(msg.Overflowed){
			CLog.Info("WARNING: msg overflowed for %s", client.name);
			msg.Clear();
		}

		SendMessageToClient(msg, client);
	}
        public void HandleTCPMsg(byte[] msgDataBuf, int bufLen)
        {
            MsgPacket packet = MessageAdapter.PackDataBuf(msgDataBuf, bufLen);

            Logging.Debug($"type:{packet.TypeStr}, data:{packet.DataStr}.");
            MessageAdapter.CreateMsgHandler(packet)?.Handle(this, null);
        }
Exemplo n.º 4
0
	public void SV_ExecuteClientMessage(ClientNode cl, MsgPacket msg)
	{
		
		msg.Oob = false;
		int srvID = msg.ReadInt();
		cl.messageAcknowledge = msg.ReadInt();
		if(cl.messageAcknowledge < 0){
			DropClient(cl,"illegible client message");
			return;
		}

		cl.reliableAcknowledge = msg.ReadInt();
		if(cl.reliableAcknowledge < cl.reliableSequence - CConstVar.MAX_RELIABLE_COMMANDS){
			DropClient(cl,"illegible client message");
			cl.reliableAcknowledge = cl.reliableSequence;
			return;
		}

		if(srvID != serverID ){
		// 	if(serverID >= restartedServerId && srvID < serverID){
		// 		CLog.Info("{0} : ignoring pre map_restart/ outdated client message",cl.name);
				
				if(cl.messageAcknowledge > cl.gamestateMessageNum){
					SendClientGameState(cl);
				}
				return;
		}
		// }

		if(cl.oldServerTime > 0 && srvID == serverID){
			CLog.Info("{0} ackownledged gamestate", cl.name);
			cl.oldServerTime = 0;
		}

		int c = 0;
		do{
			c = msg.ReadByte();
			if(c == (int)CLC_Cmd.EOF){
				break;
			}
			if(c != (int)CLC_Cmd.ClientCommand){
				break;
			}
			if(!ClientCommand(cl, msg)){
				return;
			}
			if(cl.state == ClientState.ZOMBIE){
				return;
			}
		}while(true);


		if(c == (int)CLC_Cmd.MOVE){
			UserMove(cl,msg, true);
		}else if(c == (int)CLC_Cmd.MoveNoDelta){
			UserMove(cl,msg,false);
		}else if(c != (int)CLC_Cmd.EOF){
			CLog.Info("bad command type for client!!!!");
		}
	}
Exemplo n.º 5
0
    static int PushLuaString(IntPtr L)
    {
        MsgPacket obj = LuaScriptMgr.GetNetObject <MsgPacket>(L, 1);

        obj.PushLuaString(L);
        return(1);
    }
Exemplo n.º 6
0
        public void Shout(ShoutPacket shoutPacket)
        {
            var sayPacket = new SayPacket
            {
                VisualType = VisualType.Player,
                VisualId   = 0,
                Type       = SayColorType.Yellow,
                Message    =
                    $"({Language.Instance.GetMessageFromKey(LanguageKey.ADMINISTRATOR, Session.Account.Language)}){shoutPacket.Message}"
            };

            var msgPacket = new MsgPacket
            {
                Type    = MessageType.Shout,
                Message = shoutPacket.Message
            };

            var sayPostedPacket = new PostedPacket
            {
                Packet          = PacketFactory.Serialize(sayPacket),
                SenderCharacter = new Data.WebApi.Character()
                {
                    Name = Session.Character.Name,
                    Id   = Session.Character.CharacterId
                }
            };

            var msgPostedPacket = new PostedPacket
            {
                Packet = PacketFactory.Serialize(msgPacket)
            };

            ServerManager.Instance.BroadcastPackets(new List <PostedPacket>(new[] { sayPostedPacket, msgPostedPacket }));
        }
Exemplo n.º 7
0
	private void UpdateServerCommandsToClient(ClientNode client, MsgPacket msg){
		for(int i = client.reliableAcknowledge + 1; i <= client.reliableSequence; i++){
			msg.WriteByte((byte)SVCCmd.SERVER_COMMAND);
			msg.WriteInt(i);
			msg.WriteString(client.reliableCommands[i&CConstVar.MAX_RELIABLE_COMMANDS]);
		}
		client.reliableSent = client.reliableSequence;
	}
Exemplo n.º 8
0
        public void SendPacket(int id, object obj = null)
        {
            var pack = new MsgPacket {
                Id = id, Proto = (null == obj ? null : new Proto(obj))
            };

            this.network.SendTo(pack);
        }
 public void HandleUDPMsg(byte[] msgDataBuf, int bufLen, IPEndPoint remoteEP)
 {
     if (ShouldHandleMsg(remoteEP.Address))
     {
         MsgPacket packet = MessageAdapter.PackDataBuf(msgDataBuf, bufLen);
         Logging.Debug($"type:{packet.TypeStr}, data:{packet.DataStr}.");
         MessageAdapter.CreateMsgHandler(packet)?.Handle(this, remoteEP.Address);
     }
 }
Exemplo n.º 10
0
    public void PacketConnectResponse(IPEndPoint from, MsgPacket msg)
    {
        int chNum;

        if (state >= ConnectionState.CONNECTED)
        {
            CLog.Info("Dup connect recieved. Ignored.");
            return;
        }

        // if(state != ConnectionState.CHALLENGING)
        // {
        //  CLog.Info("connectResponse packet while not connecting. Ignored.");
        //  return;
        // }
        string p       = CDataModel.CmdBuffer.Argv(2);
        int    tmpPort = from.Port;

        if (!string.IsNullOrEmpty(p))
        {
            from.Port = System.Convert.ToInt32(p);
        }

        if (!from.Equals(serverAddress))
        {
            CLog.Info("connectResponse from wrong address. Ignored.");
            return;
        }

        string c = CDataModel.CmdBuffer.Argv(1);

        if (!string.IsNullOrEmpty(c))
        {
            chNum = Convert.ToInt32(c);
        }
        else
        {
            CLog.Info("Bad connectResponse recieved. Ignored.");
            return;
        }
        if (chNum != challenge)
        {
            CLog.Info("ConnectionResponse with bad challenge received. Ignored.");
            return;
        }

        string id  = CDataModel.CmdBuffer.Argv(3);
        var    cla = CDataModel.GameState.ClActive;

        // if(!string.IsNullOrEmpty(id)){
        //  cla.serverID = Convert.ToInt32(id);
        // }

        NetChanSetup(NetSrc.CLIENT, from, tmpPort, challenge);
        state = ConnectionState.CONNECTED;
        lastPacketSentTime = -9999;         //立即发送第一个数据包
    }
Exemplo n.º 11
0
	private void EmitPacketEntities(SvClientSnapshot from, SvClientSnapshot to, MsgPacket msg){
		EntityState? oldEnt = null;
		EntityState? newEnt = null;
		int oldIndex = 0, newIndex = 0;
		int oldNum, newNum;
		int fromNumEnts;

		if(from == null){
			fromNumEnts = 0;
		}else{
			fromNumEnts = from.numEntities;
		}

		while(newIndex < to.numEntities || oldIndex < fromNumEnts){
			if(newIndex >= to.numEntities){
				newNum = 9999;
			}else{
				newEnt = snapshotEntities[(to.firstEntity + newIndex) % numSnapshotEntities];
				newNum = newEnt.Value.entityIndex;
			}

			if(oldIndex >= fromNumEnts){
				oldNum = 9999;
			}else{
				oldEnt = snapshotEntities[(from.firstEntity + oldIndex) % numSnapshotEntities];
				oldNum = oldEnt.Value.entityIndex;
			}

			//相等表示是同一个entity
			if(newNum == oldNum){
				msg.WriteDeltaEntity(oldEnt, newEnt, false);
				oldIndex++;
				newIndex++;
				continue;
			}

			//新增的entity排在前面,
			if(newNum < oldNum){
				oldEnt = svEntities[newNum].baseline;
				msg.WriteDeltaEntity(oldEnt, newEnt, true);
				oldEnt = null;
				newIndex++;
				continue;
			}

			//旧的entity消失了,写入一个字段表示此entity消失了
			if(newNum > oldNum){
				msg.WriteDeltaEntity(oldEnt, null, true);
				oldIndex++;
				continue;
			}
		}

		msg.WriteBits(CConstVar.MAX_GENTITIES - 1, CConstVar.GENTITYNUM_BITS); //packet entities尾端

	}
        public override void Respond(TransactionController controller, object state)
        {
            IPEndPoint targetEP = state as IPEndPoint;

            if (targetEP == null)
            {
                return;
            }
            controller.SendUDP(MsgPacket.Parse(MsgPacket.TYPE_GUN, dataStr).MsgData, targetEP);
        }
Exemplo n.º 13
0
	public void SV_PacketEvent(IPEndPoint from, MsgPacket packet)
	{
		int i;
		int qport;

		if(packet.CurSize >= 4 && packet.ReadFirstInt() == -1)
		{
			SV_ConnectionlessPacket(from, packet);
		}

		packet.BeginReadOOB();
		packet.ReadInt(); //sequence number

		qport = packet.ReadShort() & 0xffff;

		for(i = 0; i < CConstVar.maxClient; i ++)
		{
			var cl = clients[i];
			if(cl.state <= ClientState.ZOMBIE){
				continue;
			}

			try{
				if(!from.Address.Equals(cl.netChan.remoteAddress.Address) || cl.netChan.qport != from.Port )
				{
					continue;
				}
			}catch(Exception e){
				int a = 0;
			}
			

			//一个IP对应多个客户端,用qport来区分
			// if(cl.netChan.qport != qport)
			// {
			// 	continue;
			// }

			// if(cl.netChan.remoteAddress.Port != from.Port)
			// {
			// 	CLog.Info("SV_PacketEvent: fixing up a translated port");
			// 	cl.netChan.remoteAddress.Port = from.Port;
			// }

			if(SV_NetChanProcess(ref cl.netChan, packet))
			{
				if(cl.state > ClientState.ZOMBIE){
					cl.lastPacketTime = time;
					SV_ExecuteClientMessage(cl, packet);
				}
			}
			// return;
		}
	}
Exemplo n.º 14
0
    /* ----------------UDP START--------------------- */

    public void PacketEvent(MsgPacket packet, IPEndPoint from)
    {
        var connection = CDataModel.Connection;

        // if(Server.Instance.ServerRunning){
        //  Server.Instance.SV_PacketPrcess(packet, from);
        // }else{

        connection.lastPacketTime = CDataModel.GameState.realTime;
        if (packet.CurSize >= 4 && packet.ReadFirstInt() == -1)
        {
            ConnectionlessPacket(from, packet);
            return;
        }
        if (connection.state < ConnectionState.CONNECTED)
        {
            return;
        }
        if (packet.CurSize < 4)
        {
            CLog.Info("{0}: wrong packet", from.Address);
            return;
        }

        var netChan = CDataModel.Connection.NetChan;

        if (!from.Address.Equals(connection.NetChan.remoteAddress.Address) || from.Port != netChan.qport)
        {
            CLog.Info("{0}: sequenced packet without connection", from);
            return;
        }

        if (!NetChanProcess(ref netChan, packet))
        {
            return;
        }

        //可靠消息和不可靠消息的头是不同的
        int headerBytes = packet.CurPos;

        //记录最后接收到的消息,这样它可以在客户端信息中返回,允许服务器检测丢失的gamestate
        connection.serverMessageSequence = packet.ReadFirstInt();
        connection.lastPacketTime        = CDataModel.GameState.time;

        ParseMessage(packet);

        //在解析完packet之后,不知道是否能保存demo message
        if (connection.demoRecording && !connection.demoWaiting)
        {
            WriteDemoMessage(packet, headerBytes);
        }
        // }
    }
Exemplo n.º 15
0
        private static void packHudson(FidoAddress destAddress, FidoAddress myAddress, string outfile)
        {
            Messages  mb  = new Messages();
            MsgPacket pkt = new MsgPacket();

            pkt.dest = destAddress;
            pkt.orig = myAddress;
            foreach (MsgHdr.MsgHdrRecord h in mb.Headers.Data)
            {
                pkt.Messages.Add(new HudsonPackedMessage(mb, h.MsgNum));
            }
            File.WriteAllBytes(outfile, pkt.Binary);
        }
Exemplo n.º 16
0
    public void NetChanTransmitNextFrame(ref NetChan netChan)
    {
        MsgPacket send = new MsgPacket();

        send.Oob = true;
        byte[] send_buf         = new byte[CConstVar.PACKET_MAX_LEN];
        int    fragmentLength   = 0;
        int    outgoingSequence = netChan.outgoingSequence | CConstVar.FRAGMENT_BIT;

        send.WriteInt(outgoingSequence);

        //如果是客户端就发送qport
        if (netChan.src == NetSrc.CLIENT)
        {
            send.WriteInt(CConstVar.Qport);
        }

        send.WriteInt(CheckSum(netChan.challenge, netChan.outgoingSequence));

        fragmentLength = CConstVar.FRAGMENT_SIZE;
        if (netChan.unsentFragmentStart + fragmentLength > netChan.unsentLength)
        {
            fragmentLength = netChan.unsentLength - netChan.unsentFragmentStart;
        }

        send.WriteShort((short)netChan.unsentFragmentStart);
        send.WriteShort((short)fragmentLength);
        send.WriteBufferData(netChan.unsentBuffer, -1, fragmentLength, netChan.unsentFragmentStart);

        //发送数据
        SendPacket(netChan.src, send.CurSize, send.Data, netChan.remoteAddress);

        //存储发送的时间和大小
        netChan.lastSentTime = CDataModel.InputEvent.Milliseconds();
        netChan.lastSentSize = send.CurSize;

        if (CConstVar.ShowPacket > 0)
        {
            CLog.Info("%s send %d : s=%d fragment=%d,%d", netChan.src, send.CurSize, netChan.outgoingSequence, netChan.unsentFragmentStart, fragmentLength);
        }

        netChan.unsentFragmentStart += fragmentLength;

        //现在的情况有点戏剧,因为一个packet如果刚好是fragment的长度
        //那还需要发送第二个packet(长度为0),这样另外一端就知道是否有更多的packet。
        if (netChan.unsentFragmentStart == netChan.unsentLength && CConstVar.FRAGMENT_SIZE != fragmentLength)
        {
            netChan.outgoingSequence++;
            netChan.unsentFragments = false;
        }
    }
Exemplo n.º 17
0
    public void Copy(MsgPacket dest, byte[] data, int length)
    {
        if (length < curSize)
        {
            CLog.Error("Msg Copy: can't copy into a smaller MsgPacket buffer");
        }

        Array.Copy(data, 0, dest.Data, 0, length);
        curSize            = length;
        dest.AllowOverflow = allowOverflow;
        dest.Overflowed    = overflowed;
        dest.Oob           = oob;
        dest.Bit           = bit;
    }
Exemplo n.º 18
0
    //发送的data数据是压缩过的,所以这里oob是true,不进行压缩
    public void NetChanTransmit(ref NetChan netChan, int length, byte[] data)
    {
        MsgPacket send = new MsgPacket();

        byte[] sendBuf = new byte[CConstVar.PACKET_MAX_LEN];
        if (length > CConstVar.PACKET_MAX_LEN)
        {
            CLog.Info("Netchan transmit overflow, length = {0}", length);
        }
        netChan.unsentFragmentStart = 0;

        //fragment large reliable messages
        if (length >= CConstVar.FRAGMENT_SIZE)
        {
            netChan.unsentFragments = true;
            netChan.unsentLength    = length;
            Array.Copy(data, 0, netChan.unsentBuffer, 0, length);

            //只发送第一帧的数据
            NetChanTransmitNextFrame(ref netChan);
        }

        send.Oob = true;
        //写入packet header
        send.WriteInt(netChan.outgoingSequence);

        //发送qport
        if (netChan.src == NetSrc.CLIENT)            //客户端发送到服务器需要qport
        {
            send.WriteShort((short)CConstVar.Qport); //这里qport跟本地监听端口一致
        }

        send.WriteInt(CheckSum(netChan.challenge, netChan.outgoingSequence));         //checksum
        netChan.outgoingSequence++;

        send.WriteData(data, length);         //data的数据写入到packet中

        //发送数据
        SendPacket(netChan.src, send.CurSize, send.Data, netChan.remoteAddress);

        //存储这个包发送的时间和大小。
        netChan.lastSentTime = CDataModel.InputEvent.Milliseconds();
        netChan.lastSentSize = send.CurSize;

        if (CConstVar.ShowPacket > 0)
        {
            CLog.Info("{0} send {1} : outgoSeq = {2} incomSeq = {3}", netChan.src, send.CurSize, netChan.outgoingSequence - 1, netChan.incomingSequence);
        }
    }
Exemplo n.º 19
0
    static int _CreateMsgPacket(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 0)
        {
            MsgPacket obj = new MsgPacket();
            LuaScriptMgr.PushObject(L, obj);
            return(1);
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: MsgPacket.New");
        }

        return(0);
    }
Exemplo n.º 20
0
 public void Die()
 {
     Debug.Log (MyID+"is Dead");
     // if local, send to oher side
     if (tag == "Circle"){
         var _msgPacket = new MsgPacket();
         _msgPacket.IdObj = MyID;
         _msgPacket._msgtype = MsgType.die;
         _msgPacket._timeStamp = Time.time;
         NetworkManagerScript.instance.SendMessageViaNet(_msgPacket);
         MainGameScript.instance.MyLeft--;
     }
      else
     {
         MainGameScript.instance.HisLeft--;
     }
     Destroy(gameObject);
 }
Exemplo n.º 21
0
    public void PacketChallengeResponse(IPEndPoint from, MsgPacket msg)
    {
        if (CDataModel.Connection.state == ConnectionState.CONNECTING)
        {
            CLog.Info("Unwanted challenge response recieved. Ignored.");
            return;
        }

        // int ch = 0;
        // int ver = 0;
        var cmd      = CDataModel.CmdBuffer;
        var userinfo = cmd.Argv(2);
        var port     = CUtils.GetValueForKey(userinfo, "port");

        if (!string.IsNullOrEmpty(port))
        {
            netChan.qport = from.Port = System.Convert.ToInt32(port);
        }
        // string c = cmd.Argv(1);
        // if(!string.IsNullOrEmpty(c))
        // {
        //  ch = Convert.ToInt32(c);
        // }
        // string sver = cmd.Argv(3);
        // if(!string.IsNullOrEmpty(sver)){
        //  ver = Convert.ToInt32(sver);
        // }

        // if(string.IsNullOrEmpty(c) || ch != challenge)
        // {
        //  CLog.Info("Bad challenge for challengeResponse. Ignored.");
        //  return;
        // }

        //发送challenge response,而不是challenge request packets
        challenge          = Convert.ToInt32(cmd.Argv(1));
        netChan.challenge  = challenge;
        state              = ConnectionState.CHALLENGING;
        connectPacketCount = 0;
        connectTime        = -99999;

        //使用这个地址作为新的服务器地址。这允许服务器代理处理到多个服务器的连接
        serverAddress = from;
    }
Exemplo n.º 22
0
    private void DeltaEntity(MsgPacket msg, ClientSnapshot frame, int newNum, ref EntityState old, bool unchanged)
    {
        EntityState state = clientActive.parseEntities[clientActive.parseEntitiesIndex & (CConstVar.MAX_PARSE_ENTITIES - 1)];

        if (unchanged)
        {
            old.CopyTo(state);
        }
        else
        {
            msg.ReadDeltaEntity(ref old, ref state, newNum);
        }
        if (state.entityIndex == (CConstVar.MAX_GENTITIES - 1))
        {
            return;
        }
        clientActive.parseEntitiesIndex++;
        frame.numEntities++;
    }
Exemplo n.º 23
0
 public void Killed()
 {
     GameObject _gameobject = Instantiate(TypesConstantsScript.instance.PartSyst,transform.position,transform.rotation) as GameObject;
     // if local, send to oher side
     if (tag == "Circle"){
         var _msgPacket = new MsgPacket();
         _msgPacket.IdObj = MyID;
         _msgPacket._msgtype = MsgType.killd;
         _msgPacket._timeStamp = Time.time;
         NetworkManagerScript.instance.SendMessageViaNet(_msgPacket);
         MainGameScript.instance.MyFrags += 6-(int)size;
     }
     else
     {
         MainGameScript.instance.HisFrags +=6-(int)size;
     }
     Destroy(_gameobject,3);
     Destroy(gameObject);
 }
Exemplo n.º 24
0
	public void SV_ConnectionlessPacket(IPEndPoint from, MsgPacket packet)
	{
		packet.BeginReadOOB();
		packet.ReadInt(); //skip -1 marker

		// if(packet.ReadChars(7, 4) == "connect")
		// {
		// 	HuffmanMsg.Decompress(packet, 12);
		// }

		string s = packet.ReadStringLine();
		var cmd = CDataModel.CmdBuffer;
		cmd.TokenizeString(s, false);

		string c = cmd.Argv(0);
		CLog.Info("SV received packet {0} : {1}", from, c);
		int cport = 0;
		switch(c)
		{
			case "getstatus":
				SVCStatus(from);
				break;
			case "getinfo": //带上客户端的端口号
				cport = Convert.ToInt32(cmd.Argv(2));
				if(cport > 0) from.Port = cport;
				SVCInfo(from);
				break;
			case "getchallenge":
				SVCGetChallenge(from);
				break;
			case "connect":
				DirectConnect(from);
				break;
			case "rcon":
				RemoteCommand(from, packet);
				break;
			case "disconnect":
				break;
			default:
				CLog.Info("bad connectionless packet from {0}: {1}", from, s);
				break;
		}
	}
Exemplo n.º 25
0
	//发送服务器到客户端的第一条消息
	//如果客户端已知的消息是后面的但是有错误的gamstate,也会重新发送
	private void SendClientGameState(ClientNode cl){
		cl.state = ClientState.PRIMED;
		cl.pureAuthentic = 0;
		cl.gotCP = false;

		cl.gamestateMessageNum = cl.netChan.outgoingSequence;

		var msg = new MsgPacket();
		msg.WriteInt(cl.lastClientCommand);
		UpdateServerCommandsToClient(cl,msg);

		msg.WriteByte((byte)SVCCmd.GAME_STATE);
		msg.WriteInt(cl.reliableSequence);

		//写入configstring
		for(int start = 0; start < CConstVar.MAX_CONFIGSTRINGS; start++){
			if(!string.IsNullOrEmpty(configString[start])){
				msg.WriteByte((byte)SVCCmd.CONFIG_STRING);
				msg.WriteShort((short)start);
				msg.WriteString(configString[start]);
				msg.WriteByte(0); //手动写入一个字符串结束
			}
		}

		EntityState? nullstate = new EntityState();
		for(int start = 0; start < CConstVar.MAX_GENTITIES; start++){
			var baseEnt = svEntities[start].baseline;
			if(baseEnt.entityIndex == 0){
				continue;
			}

			msg.WriteByte((byte)SVCCmd.BASELINE);
			
			msg.WriteDeltaEntity(nullstate, baseEnt, true);
		}

		msg.WriteByte((byte)SVCCmd.EOF);
		msg.WriteInt(Array.IndexOf(clients, cl));

		msg.WriteInt(checksumFeed);
		SendMessageToClient(msg, cl);
	}
Exemplo n.º 26
0
    /// <summary>
    /// Inits the object with parameters. now its  method with 1 parameter.  Do I Need  place this Object to the net?
    /// </summary>
    /// <param name='param'> 
    /// Parameter.
    /// </param>
    public void initObjWithParams(bool needIsendThis)
    {
        if (!needIsendThis)
            return;
        var _msgPacket = new MsgPacket();
        _msgPacket.IdObj = MyID;
        _msgPacket._msgtype = MsgType.born;
        _msgPacket._objectSize = size;

        // normalize position
        float ScreenLeft = MainGameScript.instance.ScreenLeft, ScreenTop = MainGameScript.instance.ScreenTop;
        float ScreenRight = MainGameScript.instance.ScreenRight ,ScreenBottom = MainGameScript.instance.ScreenBottom;

        Vector3 _normalizedPosition = new Vector3((transform.position.x - ScreenLeft) / (ScreenRight-ScreenLeft),(transform.position.y - ScreenTop)/(ScreenBottom-ScreenTop),0);

        _msgPacket._objectPosition = new SerializableVector3(_normalizedPosition);
        _msgPacket._timeStamp = Time.time;
        _msgPacket._objSpeed = speed;
        _msgPacket._textureID = TextureID+4;
        NetworkManagerScript.instance.SendMessageViaNet(_msgPacket);
    }
Exemplo n.º 27
0
    protected void ParseCommandString(MsgPacket packet)
    {
        int    seq        = packet.ReadInt();
        string s          = packet.ReadString();
        var    connection = CDataModel.Connection;

        if (connection == null)
        {
            return;
        }
        if (connection.serverCommandSequence >= seq)
        {
            return;
        }
        connection.serverCommandSequence = seq;

        int index = seq & (CConstVar.MAX_RELIABLE_COMMANDS - 1);

        s.ToCharArray().CopyTo(connection.serverCommands[index], 0);
        connection.serverCommands[index][s.Length] = '\0';
    }
Exemplo n.º 28
0
    static int set_errno(IntPtr L)
    {
        object    o   = LuaScriptMgr.GetLuaObject(L, 1);
        MsgPacket obj = (MsgPacket)o;

        if (obj == null)
        {
            LuaTypes types = LuaDLL.lua_type(L, 1);

            if (types == LuaTypes.LUA_TTABLE)
            {
                LuaDLL.luaL_error(L, "unknown member name errno");
            }
            else
            {
                LuaDLL.luaL_error(L, "attempt to index errno on a nil value");
            }
        }

        obj.errno = (ushort)LuaScriptMgr.GetNumber(L, 3);
        return(0);
    }
Exemplo n.º 29
0
    static int set_data(IntPtr L)
    {
        object    o   = LuaScriptMgr.GetLuaObject(L, 1);
        MsgPacket obj = (MsgPacket)o;

        if (obj == null)
        {
            LuaTypes types = LuaDLL.lua_type(L, 1);

            if (types == LuaTypes.LUA_TTABLE)
            {
                LuaDLL.luaL_error(L, "unknown member name data");
            }
            else
            {
                LuaDLL.luaL_error(L, "attempt to index data on a nil value");
            }
        }

        obj.data = LuaScriptMgr.GetNetObject <Byte[]>(L, 3);
        return(0);
    }
Exemplo n.º 30
0
    static int get_seq(IntPtr L)
    {
        object    o   = LuaScriptMgr.GetLuaObject(L, 1);
        MsgPacket obj = (MsgPacket)o;

        if (obj == null)
        {
            LuaTypes types = LuaDLL.lua_type(L, 1);

            if (types == LuaTypes.LUA_TTABLE)
            {
                LuaDLL.luaL_error(L, "unknown member name seq");
            }
            else
            {
                LuaDLL.luaL_error(L, "attempt to index seq on a nil value");
            }
        }

        LuaScriptMgr.Push(L, obj.seq);
        return(1);
    }
Exemplo n.º 31
0
        public override Task ExecuteAsync(ShoutPacket shoutPacket, ClientSession session)
        {
            var message =
                $"({GameLanguage.Instance.GetMessageFromKey(LanguageKey.ADMINISTRATOR, session.Account.Language)}) {shoutPacket.Message}";
            var sayPacket = new SayPacket
            {
                VisualType = VisualType.Player,
                VisualId   = 0,
                Type       = SayColorType.Yellow,
                Message    = message
            };

            var msgPacket = new MsgPacket
            {
                Type    = MessageType.Shout,
                Message = message
            };

            var sayPostedPacket = new PostedPacket
            {
                Packet          = _packetSerializer.Serialize(new[] { sayPacket }),
                SenderCharacter = new Character
                {
                    Name = session.Character.Name,
                    Id   = session.Character.CharacterId
                },
                ReceiverType = ReceiverType.All
            };

            var msgPostedPacket = new PostedPacket
            {
                Packet       = _packetSerializer.Serialize(new[] { msgPacket }),
                ReceiverType = ReceiverType.All
            };

            _packetHttpClient.BroadcastPacketsAsync(new List <PostedPacket>(new[] { sayPostedPacket, msgPostedPacket }));
            return(Task.CompletedTask);
        }
Exemplo n.º 32
0
	public void RunServerPacket(IPEndPoint from, MsgPacket packet)
	{
		int t1,t2,msec;
		t1 = 0;

		var input = CDataModel.InputEvent;
		if(CConstVar.ComSpeeds > 0)
		{
			t1 = input.Milliseconds();
		}

		SV_PacketEvent(from, packet);

		if(CConstVar.ComSpeeds > 0)
		{
			t2 = input.Milliseconds();
			msec = t2 - t1;
			if(CConstVar.ComSpeeds == 3)
			{
				CLog.Info("SV_PacketEvent time: {0}", msec);
			}
		}
	}
        public static IMsgHandler CreateMsgHandler(MsgPacket packet)
        {
            IMsgHandler msgHandler = null;

            switch (packet.TypeStr)
            {
            case MsgPacket.TYPE_IP:
                msgHandler = new IPMsgHandler(packet.DataStr);
                break;

            case MsgPacket.TYPE_CMD:
                msgHandler = new CmdMsgHandler(packet.DataStr);
                break;

            case MsgPacket.TYPE_ANS:
                msgHandler = new AnsMsgHandler(packet.DataStr);
                break;

            case MsgPacket.TYPE_GUN:
                msgHandler = new GunMsgHandler(packet.DataStr);
                break;
            }
            return(msgHandler);
        }
Exemplo n.º 34
0
 /// <summary>
 /// Sends the message via net.
 /// Serialize _msgPacket pushes it to network
 /// </summary>
 /// <param name='_msgPacket'>
 /// _msg packet.
 /// </param>
 public void SendMessageViaNet(MsgPacket _msgpacket)
 {
     SendMessageViaNet(NetwInterfaceEx,_msgpacket);
 }
Exemplo n.º 35
0
    IEnumerator MainGameCoroutine()
    {
        float _timer;
        // checking resources
        while(ResManagerScript.ImBusy)
            yield return new WaitForSeconds(.1f);
        // checking network
        while(NetworkManagerScript.instance.NetwInterfaceEx == null || !NetworkManagerScript.instance.NetwInterfaceEx.ConnectionStatus) // client or server doesnt matter
            yield return new WaitForSeconds(.1f);

        // turn on the central strip
        GameObject tmpObj = GameObject.Find("CentralPlane").gameObject;
        // sending myname to other side
        tmpObj.renderer.enabled = true;
        var _msgPacket = new MsgPacket();
        _msgPacket._msgtype = MsgType.namechange;
        _msgPacket.RawData = MyName;
        NetworkManagerScript.instance.SendMessageViaNet(_msgPacket);

        Color _color = new Color(Random.value,Random.value,Random.value,1); // first time textures creatin

        StartCoroutine(ResManagerScript.instance.MaterialCreate(_color,true));

        while(ResManagerScript.ImBusy)
            {

                yield return new WaitForSeconds(.2f);
            }
        // tell first time other side to create texture

        TellOtherSideToGenerateTextures(_color);
        while(ResManagerScript.ImBusy)
            {

                yield return new WaitForSeconds(.2f);
            }
        // timeout to receive other side init packages from net. must be optimized
        yield return new WaitForSeconds(.5f);

        // texture Swap
        ResManagerScript.instance.TextureSwap(true);
        TellOtherSideToChangeTextures();

        //!!!!!
        while(ResManagerScript.ImBusy)
            yield return new WaitForSeconds(.1f);

        _color = new Color(Random.value,Random.value,Random.value,1); // prepare next matrial

        StartCoroutine(ResManagerScript.instance.MaterialCreate(_color,true));
        while(ResManagerScript.ImBusy)
            {

                yield return new WaitForSeconds(.2f);
            }
        TellOtherSideToGenerateTextures(_color);

        // is resManager free? all resources are created
        while(ResManagerScript.ImBusy)
            yield return new WaitForSeconds(.1f);

        // start
        _gamestatus = GameStatus.going;
        InvokeRepeating("BornMyCircle",1,1.5f);// debug
        _timer = Time.time;
        while (_gamestatus == GameStatus.going){
            if(Time.time > _timer+20){
                _timer = Time.time;
                // Increaseing speed changing TexturePack
                NextLevel();
            }
            yield return new WaitForSeconds(.02f);
        }
        CancelInvoke("BornMyCircle");
    }
Exemplo n.º 36
0
 public void TellOtherSideToGenerateTextures(Color _color)
 {
     var _msgPacket = new MsgPacket();
     _msgPacket._msgtype = MsgType.textureGenerate;
     _msgPacket._textureColor = new SeriaziableColor(_color);
     _msgPacket._timeStamp = Time.time;
     NetworkManagerScript.instance.SendMessageViaNet(_msgPacket);
 }
Exemplo n.º 37
0
 public void TellOtherSideToChangeTextures()
 {
     var _msgPacket = new MsgPacket();
     _msgPacket._msgtype = MsgType.textureChanging;
     _msgPacket._timeStamp = Time.time;
     NetworkManagerScript.instance.SendMessageViaNet(_msgPacket);
 }
Exemplo n.º 38
0
    public MsgPacket ProcessingReceivedMessage(Byte [] Data)
    {
        /// exemplair of _msgPacket
            var _msgPacket = new MsgPacket();
            var MyMemoryStream =  new System.IO.MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();

            MyMemoryStream.Write(Data,0,Data.Length);
            MyMemoryStream.Position = 0;
            _msgPacket = (MsgPacket) formatter.Deserialize(MyMemoryStream);

            BeginReceive();

            return _msgPacket;
    }
Exemplo n.º 39
0
    //overload previous method with point of network interface to push packet
    public void SendMessageViaNet(NetwInterface _netInterface,MsgPacket _msgPacket)
    {
        _msgPacket._packagenum = PackageCounter++;
        // serialize
            byte []MyData;
            System.IO.MemoryStream MyMemoryStream;
            MyMemoryStream =  new System.IO.MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(MyMemoryStream, _msgPacket);
            MyData = MyMemoryStream.ToArray();

        // SendTo net

            _netInterface.Send(MyData);
    }
Exemplo n.º 40
0
    /// <summary>
    /// Debug! Born New circles and send they via net 
    /// </summary>
    public void DemoServerRunBot()
    {
        if( NetwInterfaceEx == null)
            return;
        if ( !NetwInterfaceEx.ConnectionStatus)
            return;
        float RndVal = UnityEngine.Random.Range(2f,6f);

        var _msgPacket = new MsgPacket();
        float _floatPos = .25f; // left quarter of screen

        _msgPacket._objectPosition  = new SerializableVector3(new Vector3(_floatPos,0,0));

        _msgPacket.IdObj = DemoServerCircleID++;
        _msgPacket._msgtype = MsgType.born;
        _msgPacket._objectSize = RndVal;
        _msgPacket._objSpeed = ((10-RndVal))*-0.5f;
        _msgPacket._textureID = UnityEngine.Random.Range(4,7);

        _msgPacket._timeStamp = Time.time;
        SendMessageViaNet(DemoServerInterfaceEx, _msgPacket);
    }
Exemplo n.º 41
0
    public void ChangeTextureInDemoServer()
    {
        var _msgPacket = new MsgPacket();
        MessageServiceClass.MessageProcessing("Demo Server Texure was changed");
        _msgPacket._msgtype = MsgType.textureChanging;
        _msgPacket._timeStamp = Time.time;
        SendMessageViaNet(DemoServerInterfaceEx, _msgPacket);

        Color _color = new Color(UnityEngine.Random.value,UnityEngine.Random.value,UnityEngine.Random.value,1);

        _msgPacket._msgtype = MsgType.textureGenerate;
        _msgPacket._textureColor = new SeriaziableColor(_color);
        _msgPacket._timeStamp = Time.time;
        SendMessageViaNet(DemoServerInterfaceEx, _msgPacket);
    }