Esempio n. 1
0
    public static bool SendClient(NETMSG mg, long userID, int channelID = 0)
    {
        if (!isStarted)
        {
            Debug.LogError("You need to start a server first.");
            return(false);
        }
        if (!isHost || !playerIDs.ContainsKey(userID))
        {
            Debug.LogError("Invalid player ID or is not the host! " + isHost.ToString() + ", " + userID + " " + mg.OP);
            return(false);
        }
        if (channelID < 0 || allocChannels.Length <= channelID)
        {
            Debug.LogError("Invalid channel ID!" + channelID);
            return(false);
        }
        byte[]          buffer = new byte[BYTE_SIZE + mg.dataSize];
        BinaryFormatter form   = new BinaryFormatter();
        MemoryStream    ms     = new MemoryStream(buffer);

        form.Serialize(ms, mg);

        bool bj = NetworkTransport.Send(playerHID[userID], playerIDs[userID], channelID, buffer, BYTE_SIZE + mg.dataSize, out error);

        ms.Close();
        return(bj);
    }
Esempio n. 2
0
        private void send(NETMSG msg)
        {
            MemoryStream mem = new MemoryStream();

            Bf.Serialize(mem, msg);  //ns
            byte[] b   = mem.ToArray();
            byte[] len = BitConverter.GetBytes(b.Length);
            socket.GetStream().Write(len, 0, 4);
            socket.GetStream().Write(b, 0, b.Length);
        }
Esempio n. 3
0
    public static bool SendServer(NETMSG mg, int channelID = 0)
    {
        if (!isStarted)
        {
            Debug.LogError("You need to start a server first.");
            return(false);
        }
        if (!hasConnected)
        {
            Debug.LogError("Can't send to host if you haven't connected yet!");
            return(false);
        }
        if (isHost)
        {
            Debug.LogError("Can't send to the host if you are the host! " + isHost.ToString());
            return(false);
        }
        if (channelID < 0 || allocChannels.Length <= channelID)
        {
            Debug.LogError("Invalid channel ID!" + channelID);
            return(false);
        }
        if (BYTE_SIZE + mg.dataSize > 1028)
        {
            switch (channels[channelID])
            {
            case QosType.ReliableFragmented:
            case QosType.ReliableFragmentedSequenced:
            case QosType.UnreliableFragmented:
            case QosType.UnreliableFragmentedSequenced:
                break;

            default:
                Debug.LogError("Packet size is too large for this channel! Please use a fragmented channel.");
                return(false);
            }
        }
        byte[]          buffer = new byte[BYTE_SIZE + mg.dataSize];
        BinaryFormatter form   = new BinaryFormatter();
        MemoryStream    ms     = new MemoryStream(buffer);

        form.Serialize(ms, mg);

        bool dj = NetworkTransport.Send(hostID, connectionID, channelID, buffer, BYTE_SIZE + mg.dataSize, out error);

        ms.Close();
        return(dj);
    }
Esempio n. 4
0
        public void Start()
        {
            Console.WriteLine("CLIENT START");
            socket = new TcpClient();

            try {
                socket.Connect(serverEndPoint);
                Thread.Sleep(100);
                this.networkStream = new BufferedStream(socket.GetStream());
                NETMSG n = receive();//= (Server.NETMSG)Bf.Deserialize( networkStream );


                if (NETMSG.MSG_TYPES.SERVER_OK.Equals(n.Type))
                {
                    send(new NETMSG(NETMSG.MSG_TYPES.CLIENT_OK, null));

                    //get game
                    send(new NETMSG(NETMSG.MSG_TYPES.CLIENT_REQUEST_SYNC, null));
                    NETMSG g = receive();
                    processServerMessage(g);

                    send(new NETMSG(NETMSG.MSG_TYPES.CLIENT_REQUEST_UID, null));

                    //given player uid
                    NETMSG uid_msg = receive();
                    processServerMessage(uid_msg);
                    Console.WriteLine("You are player #" + playerID);


                    if (this.Game != null)
                    {
                        send(new NETMSG(NETMSG.MSG_TYPES.CLIENT_READY, null));

                        //ready to play
                        //thread not to freeze UI
                        MainLoopThread = new Thread(() => this.MainLoop(/*this*/));


                        MainLoopThread.Start();
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("ERROR >> " + e.Message);
                Console.WriteLine(e.StackTrace);
                ExitRequested = true;
            }
        }
Esempio n. 5
0
    public static void SendAllClientsExcept(NETMSG mg, long except, int channelID = 0)
    {
        if (!isStarted)
        {
            Debug.LogError("You need to start a server first.");
            return;
        }
        if (!isHost)
        {
            Debug.LogError("Is not the host! " + isHost.ToString());
            return;
        }
        if (channelID < 0 || allocChannels.Length <= channelID)
        {
            Debug.LogError("Invalid channel ID!" + channelID);
            return;
        }
        byte[]          buffer = new byte[BYTE_SIZE + mg.dataSize];
        BinaryFormatter form   = new BinaryFormatter();
        MemoryStream    ms     = new MemoryStream(buffer);

        form.Serialize(ms, mg);

        // Attempt to send to all clients
        int i = 0;

        while (i < curPlayerIDs.Count)
        {
            if (curPlayerIDs[i] == except)
            {
                i++;
                continue;
            }
            NetworkTransport.Send(playerHID[curPlayerIDs[i]], playerIDs[curPlayerIDs[i]], channelID, buffer, BYTE_SIZE + mg.dataSize, out error);
            if (error == 6 || error == 2)
            {
                HandleDisconnectEvent(0, playerIDs[curPlayerIDs[i]], 0);
                //curPlayerIDs.RemoveAt(i);
                continue;
            }
            i++;
        }
        ms.Close();
    }
Esempio n. 6
0
        private NETMSG receive()
        {
            try {
                int          br  = 0;;
                byte[]       b   = new byte[256];
                MemoryStream mem = new MemoryStream();
                int          len;
                byte[]       lenb = new byte[4];

                //read length (server always sends length first as 4bytes)
                socket.GetStream().Read(lenb, 0, 4);
                len = BitConverter.ToInt32(lenb, 0);

                int toread = len;
                int read   = 0;

                do
                {
                    if (toread < 256)
                    {
                        br = socket.GetStream().Read(b, 0, toread);
                    }
                    else
                    {
                        br = socket.GetStream().Read(b, 0, 256);
                    }
                    mem.Write(b, 0, br);
                    read += br;
                } while (br == 256);

                mem.Position = 0;
                NETMSG msg = (Server.NETMSG)Bf.Deserialize(mem);
                //Console.WriteLine( "CLient received: " + msg.Type.ToString() );

                return(msg);
            } catch (Exception e) {
                Console.WriteLine("Exception while receiving: " + e.Message + " at " + e.StackTrace);
                return(new NETMSG(NETMSG.MSG_TYPES.SERVER_ERROR, objToBytes(e), e.Message));
            }
        }
Esempio n. 7
0
        //MAIN LOGIC
        public void MainLoop(/*Client c*/)
        {
            Console.WriteLine("CLIENT " + this + " entered MainLoop");

            while (!this.exitRequested && socket.Connected)
            {
                //client sends first
                if (sendStack.Count() > 0)
                {
                    toSend = sendStack[0];
                    sendStack.RemoveAt(0);
                }
                else
                {
                    toSend = new NETMSG(NETMSG.MSG_TYPES.CLIENT_OK, null);
                }
                send(toSend);
                NETMSG m = receive();
                processServerMessage(m);
                Thread.Sleep(10);
            }
        }
Esempio n. 8
0
        //MAIN LOGIC
        public void MainLoop()
        {
            printl("i entered MainLoop.");
            IsPlaying = false;

            while (!this.exitRequested && socket.Connected)
            {
                //client sends first
                if (sendStack.Count() > 0)
                {
                    toSend = sendStack[0];
                    sendStack.RemoveAt(0);
                }
                else
                {
                    toSend = new NETMSG(NETMSG.MSG_TYPES.CLIENT_OK, null);
                }
                send(toSend);
                NETMSG m = receive();
                processServerMessage(m);
                Thread.Sleep(10);
            }
        }
Esempio n. 9
0
        private void processServerMessage(NETMSG msg)
        {
            switch (msg.Type)
            {
            case NETMSG.MSG_TYPES.SERVER_OK:
                //this is a sync message
                break;

            case NETMSG.MSG_TYPES.SERVER_GAME:
                this.Game = (CardUtils.Game)NETMSG.bytesToObj(msg.Payload);

                break;

            case NETMSG.MSG_TYPES.SERVER_FULL:
                MessageBox.Show("The server is full. Closing connection.");
                ExitRequested = true;
                break;

            case NETMSG.MSG_TYPES.SERVER_ERROR:
                MessageBox.Show("SERVER_ERROR received from Server: \n" + msg.Message + ".");
                break;

            case NETMSG.MSG_TYPES.SERVER_CLOSING:
                MessageBox.Show("The server will close or you were kicked.  Disconnecting from server.");
                ExitRequested = true;
                break;

            case NETMSG.MSG_TYPES.SERVER_PLAYER_UID:
                this.playerID = ((CardUtils.Player)NETMSG.bytesToObj(msg.Payload)).ID;
                break;

            case NETMSG.MSG_TYPES.PLAYER_BETS:
                this.Game.Bet(((BET)NETMSG.bytesToObj(msg.Payload)).PlayerID, ((BET)NETMSG.bytesToObj(msg.Payload)).betTOAdd);
                break;

            case NETMSG.MSG_TYPES.PLAYER_CONNECTED:
                CardUtils.Player pla = (CardUtils.Player)NETMSG.bytesToObj(msg.Payload);
                Console.WriteLine("new player!: " + pla.ID);
                Game.AddPlayer(pla);
                break;

            case NETMSG.MSG_TYPES.PLAYER_DISCONNECTED:
                uint id = (uint)NETMSG.bytesToObj(msg.Payload);
                this.Game.Disconnect(id);
                break;

            case NETMSG.MSG_TYPES.PLAYER_PASS:
                this.Game.Pass(((CardUtils.Player)NETMSG.bytesToObj(msg.Payload)).ID);
                break;

            case NETMSG.MSG_TYPES.PLAYER_PICKS:
                this.Game.Pass((uint)NETMSG.bytesToObj(msg.Payload));
                break;

            case NETMSG.MSG_TYPES.END_GAME:
                //say who won
                break;

            default:
                MessageBox.Show("Unknown NETMSG struct object received");
                break;
            }
        }
Esempio n. 10
0
 public void AddToSendQueue(NETMSG msg)
 {
     this.sendStack.Add(msg);
 }
Esempio n. 11
0
    private static void HandleDataEvent(int rec, int sID, int cID, byte[] msg, int size)
    {
        BinaryFormatter form = new BinaryFormatter();
        MemoryStream    ms   = new MemoryStream(msg);

        NETMSG msg1 = form.Deserialize(ms) as NETMSG;

        //Debug.Log(Time.time + " " + msg1.GetType().Name.ToString());
        ms.Close();
        switch (msg1.OP)
        {
        case NetID.None:
            break;

        case NetID.Buffer:
            break;

        case NetID.ConnID:
            if (msg1 is ConnNETMSG)
            {
                Debug.Log("Client connection UUID: " + ((ConnNETMSG)msg1).uuid);
                curUserUUID = ((ConnNETMSG)msg1).uuid;
                // NOW set the user as connected.
                hasConnected = true;

                return;
            }
            break;

        case NetID.ObjMsg:
            //Handle
            PFM.ManageGameObjects((ObjNETMSG)msg1);
            return;

        case NetID.Msg:
            //Handle
            OnMsgEvent(new MsgObj()
            {
                msg = ((MessageNETMSG)msg1).msg, uuid = FetchUUID(sID)
            });
            return;

        case NetID.User:
            // User defined.
            // All user events should inherit from the UserNETMSG msg
            if (msg1 is UserNETMSG)
            {
                //Debug.Log("o-o " + sID + " " + IDplayers.ContainsKey(sID));
                OnUserEvent(msg1.OP, ((UserNETMSG)msg1).subID, new ArbObj()
                {
                    msg = msg1, id = msg1.OP, uuid = FetchUUID(sID)
                });
            }
            else
            {
                Debug.LogError("Unregistered packet is not a subclass of UserNETMSG! All user/user defined IDs must be of this type!");
            }
            return;

        default:
            // All user events should inherit from the UserNetMSG msg
            if (msg1 is UserNETMSG)
            {
                OnOtherEvent(msg1.OP, ((UserNETMSG)msg1).subID, new ArbObj()
                {
                    msg = msg1, id = msg1.OP, uuid = FetchUUID(sID)
                });
            }
            else
            {
                Debug.LogError("Unregistered packet is not a subclass of UserNETMSG! All user/user defined IDs must be of this type!");
            }
            return;
        }
        Debug.LogError("UNHANDLED MESSAGE: " + msg1.OP);
    }
Esempio n. 12
0
        private void processServerMessage(NETMSG msg)
        {
            switch (msg.Type)
            {
            case NETMSG.MSG_TYPES.SERVER_OK:
                //this is a sync message

                break;

            case NETMSG.MSG_TYPES.SERVER_GAME:
                this.Game = (CardUtils.Game)NETMSG.bytesToObj(msg.Payload);

                break;

            case NETMSG.MSG_TYPES.SERVER_FULL:
                MessageBox.Show("The server is full. Closing connection.");
                ExitRequested = true;
                break;

            case NETMSG.MSG_TYPES.SERVER_ERROR:
                MessageBox.Show("SERVER_ERROR received from Server: \n" + msg.Message + ".");
                break;

            case NETMSG.MSG_TYPES.SERVER_CLOSING:
                MessageBox.Show("The server will close or you were kicked.  Disconnecting from server.");
                ExitRequested = true;
                break;

            case NETMSG.MSG_TYPES.SERVER_PLAYER_UID:
                this.playerID = ((CardUtils.Player)NETMSG.bytesToObj(msg.Payload)).ID;
                break;

            case NETMSG.MSG_TYPES.PLAYER_BETS:
                this.Game.Bet(((BET)NETMSG.bytesToObj(msg.Payload)).PlayerID, ((BET)NETMSG.bytesToObj(msg.Payload)).betTOAdd);
                //ui.RefreshView();
                RefreshUI();
                break;

            case NETMSG.MSG_TYPES.PLAYER_CONNECTED:
                CardUtils.Player pla = (CardUtils.Player)NETMSG.bytesToObj(msg.Payload);
                if (Game.Players.Where(_player => _player.ID == pla.ID).Count() > 0)
                {
                    printl("... real funny, william, but player " + pla.ID + " seems to already be in the list...");
                    break;
                }
                printl("adding a new player: " + pla.ID);
                Game.AddPlayer(pla);
                //printl( playerID + " sees total count:" + Game.Players.Count );
                if (Game.Players.Count == 1)
                {
                    printl("i should now be the one playing. " + pla.ID);
                    Game.PlayingPlayer = Game.Players[0];
                }
                else if (Game.Players.Count > 3)
                {
                    foreach (CardUtils.Player _p in Game.Players)
                    {
                        printl("- " + _p.ID);
                    }
                }


                //ui.RefreshView();
                RefreshUI();
                break;

            case NETMSG.MSG_TYPES.PLAYER_DISCONNECTED:
                uint id = (uint)NETMSG.bytesToObj(msg.Payload);
                this.Game.Disconnect(id);
                //ui.RefreshView();
                RefreshUI();
                break;

            case NETMSG.MSG_TYPES.PLAYER_PASS:
                uint passedID = (uint)NETMSG.bytesToObj(msg.Payload);
                this.Game.Pass(passedID);
                printl(passedID + "told me he passed, i think " + Game.PlayingPlayer.ID + " is now playing.");
                if (this.Game.PlayingPlayer.ID == this.playerID)
                {
                    printl("i will now be playing.");
                    this.IsPlaying = true;
                }
                ShowWinner();
                RefreshUI();
                break;

            case NETMSG.MSG_TYPES.PLAYER_PICKS:
                PICK pick = ((PICK)NETMSG.bytesToObj(msg.Payload));
                this.Game.PickCard(pick.PlayerID, pick.Card);
                ShowWinner();
                RefreshUI();
                break;

            case NETMSG.MSG_TYPES.END_GAME:
                //say who won
                //ui.RefreshView
                RefreshUI();
                break;

            case NETMSG.MSG_TYPES.PLAYER_YOURTURN:
                //this.Game.PlayingPlayer = this.Game.FindPlayer( playerID );
                printl("i will be the first player.");
                IsPlaying = true;
                //ui.RefreshView();
                RefreshUI();
                break;

            default:
                MessageBox.Show("Unknown NETMSG struct object received");
                break;
            }
        }