예제 #1
0
 private static void SendMessage(NetServer server, MsgBase msg)
 {
     NetOutgoingMessage om = server.CreateMessage();
     om.Write(msg.Id);
     msg.W(om);
     server.SendToAll(om, NetDeliveryMethod.Unreliable);
 }
예제 #2
0
파일: NetServer.cs 프로젝트: javawork/Dice
        public void Broadcast(ushort code, IMessage message)
        {
            var buffer     = NetUtil.SerializeMessageToBytes(code, message);
            var netMessage = _netServer.CreateMessage(buffer.Length);

            netMessage.Write(buffer);
            _netServer.SendToAll(netMessage, NetDeliveryMethod.ReliableOrdered);
        }
예제 #3
0
파일: Server.cs 프로젝트: uwrov/teaching
        public static void Main(string[] args)
        {
            Console.WriteLine("[SERVER] Testing Lidgren-Network-v3...");
            NetPeerConfiguration serverConfig = new NetPeerConfiguration("test");
            serverConfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            serverConfig.MaximumConnections = 32;
            serverConfig.Port = 12345;
            NetServer server = new NetServer(serverConfig);
            server.Start();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            server.RegisterReceivedCallback(new SendOrPostCallback(GotMessage));

            while(true) {
                string msg = Console.ReadLine();

                NetOutgoingMessage sendMsg = server.CreateMessage();
                sendMsg.Write("[SERVER] " + msg);

                server.SendToAll(sendMsg, NetDeliveryMethod.ReliableOrdered);
            }
        }
예제 #4
0
        static void Main(string[] args)
        {
            // create a configuration for the server
            NetConfiguration config = new NetConfiguration("chatApp");
            config.MaxConnections = 128;
            config.Port = 14242;

            // create server and start listening for connections
            NetServer server = new NetServer(config);
            server.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
            server.Start();

            // create a buffer to read data into
            NetBuffer buffer = server.CreateBuffer();

            // keep running until the user presses a key
            Console.WriteLine("Press ESC to quit server");
            bool keepRunning = true;
            while (keepRunning)
            {
                NetMessageType type;
                NetConnection sender;

                // check if any messages has been received
                while(server.ReadMessage(buffer, out type, out sender))
                {
                    switch (type)
                    {
                        case NetMessageType.DebugMessage:
                            Console.WriteLine(buffer.ReadString());
                            break;
                        case NetMessageType.ConnectionApproval:
                            Console.WriteLine("Approval; hail is " + buffer.ReadString());
                            sender.Approve();
                            break;
                        case NetMessageType.StatusChanged:
                            Console.WriteLine("New status for " + sender + ": " + sender.Status + " (" + buffer.ReadString() + ")");
                            break;
                        case NetMessageType.Data:
                            // A client sent this data!
                            string msg = buffer.ReadString();

                            // send to everyone, including sender
                            NetBuffer sendBuffer = server.CreateBuffer();
                            sendBuffer.Write(sender.RemoteEndpoint.ToString() + " wrote: " + msg);

                            // send using ReliableInOrder
                            server.SendToAll(sendBuffer, NetChannel.ReliableInOrder1);
                            break;
                    }
                }

                // User pressed ESC?
                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo info = Console.ReadKey();
                    if (info.Key == ConsoleKey.Escape)
                        keepRunning = false;
                }

                Thread.Sleep(1);
            }

            server.Shutdown("Application exiting");
        }
예제 #5
0
        private static void Main(string[] args)
        {
            //TODO: Chat
            //TODO: UPnP
            //TODO: Fix Simulated Conditions

            config = new NetPeerConfiguration("spacebargame") {Port = 666, EnableUPnP = true, MaximumConnections = 50};

            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            server = new NetServer(config);
            server.Start();
            server.UPnP.ForwardPort(666, "Spacebar Game 2013");

            NetIncomingMessage inc; // Incoming Message

            //Write to con..
            var consoleInput = new Thread(ConsoleIn); //Console.ReadLine is blocked, Thread it
            consoleInput.Start(); //Start the Thread

            UserToConnection = new Dictionary<long, Client>(); //UserStore

            while (true) //While True
            {
                if ((inc = server.ReadMessage()) != null) //if message is not null
                {
                    //Console.WriteLine(inc.MessageType); //Print MessageType
                    switch (inc.MessageType)
                    {
                        case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request

                            if (inc.ReadByte() == (byte) PacketTypes.LOGIN) //and LOGIN PacketHeader
                            {
                                Console.WriteLine("Incoming LOGIN"); //Incoming Login

                                Name = inc.ReadString(); //Name is String Sent by Client
                                Console.WriteLine(Name); //Print Name

                                if (server.ConnectionsCount == 0) //ConnectionCount = 0
                                {
                                    Started = false; //Reset
                                }

                                if (UserToConnection.Values.Any(c => c.Name == Name) || Started || Name.Length >= 12)
                                    //If Name exists, or Game has Started or the Length is more then 12
                                {
                                    inc.SenderConnection.Deny("Duplicate Name"); //Deny
                                }
                                else
                                {
                                    inc.SenderConnection.Approve(); //Else Allow
                                    UserToConnection.Add(inc.SenderConnection.RemoteUniqueIdentifier,
                                        new Client(Name, inc.SenderConnection, 0, new byte[00000000]));
                                    //Add them to the Dictionary for PlayerStore
                                }

                                Thread.Sleep(500); //Sleep for Half a Second

                                if (server.ConnectionsCount == 1) //If Server.ConnectionCount is 1 they are host
                                {
                                    NetOutgoingMessage msg = server.CreateMessage(); //Host Message
                                    msg.Write((byte) PacketTypes.HOST); //Write HOST PacketHeader
                                    msg.Write("Congratulations, You are the host");
                                    server.SendMessage(msg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                                }
                            }
                            break;

                        case NetIncomingMessageType.Data:

                            var packetheader = inc.ReadByte();

                            switch ((PacketTypes) packetheader)
                            {
                                case PacketTypes.AVATAR:
                                    var bufferLength = inc.ReadInt32();
                                    var buffer = inc.ReadBytes(bufferLength);
                                    Console.WriteLine("Buffer Length:" + bufferLength);

                                    UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Buffer = buffer;
                                    foreach (KeyValuePair<long, Client> entry in UserToConnection)
                                    {
                                        if (entry.Key != inc.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            NetOutgoingMessage syncClient = server.CreateMessage();

                                            syncClient.Write((byte) PacketTypes.RECEIVEPLAYER);
                                            syncClient.Write(Name);
                                            syncClient.Write(inc.SenderConnection.RemoteUniqueIdentifier);

                                            var buffer1 =
                                                UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Buffer;

                                            syncClient.Write(buffer1.Length);
                                            syncClient.Write(buffer1);

                                            Console.WriteLine("SENT Client Name: {0}| Client ID: {1}", Name,
                                                inc.SenderConnection.RemoteUniqueIdentifier);
                                            Console.WriteLine("TO: {0}, {1}", entry.Value.Name, entry.Value.Score);
                                            server.SendMessage(syncClient, entry.Value.Connection,
                                                NetDeliveryMethod.ReliableOrdered); //OTHERPEOPLE
                                        }
                                    }

                                    foreach (KeyValuePair<long, Client> entry in UserToConnection)
                                    {
                                        //if (entry.Key != inc.SenderConnection.RemoteUniqueIdentifier)
                                        {
                                            NetOutgoingMessage syncClient = server.CreateMessage();

                                            syncClient.Write((byte) PacketTypes.RECEIVEPLAYER);
                                            syncClient.Write(entry.Value.Name);
                                            syncClient.Write(entry.Key);

                                            var buffer1 = entry.Value.Buffer;

                                            syncClient.Write(buffer1.Length);
                                            syncClient.Write(buffer1);
                                            Console.WriteLine(buffer1.Length);

                                            Console.WriteLine("SENT Client Name: {0}| Client ID: {1}", entry.Value.Name,
                                                entry.Key);
                                            Console.WriteLine("TO: {0}", inc.SenderConnection);

                                            server.SendMessage(syncClient, inc.SenderConnection,
                                                NetDeliveryMethod.ReliableOrdered); //CLIENT
                                        }
                                    }

                                    break;

                                case PacketTypes.SENDPOS:
                                    UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score =
                                        Convert.ToInt16(inc.ReadString());
                                    Console.WriteLine("{0}'s score is now: {1}",
                                        UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Name,
                                        UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score);
                                    ID = inc.SenderConnection.RemoteUniqueIdentifier;
                                    UpdateScore();

                                    break;

                                case PacketTypes.STARTGAME:
                                    //GOGOGOGO
                                    Console.WriteLine("START THE GAME");
                                    Started = true;

                                    foreach (KeyValuePair<long, Client> entry in UserToConnection)
                                    {
                                        {
                                            NetOutgoingMessage syncClient = server.CreateMessage();
                                            syncClient.Write((byte) PacketTypes.STARTGAME);
                                            syncClient.Write("Go");
                                            syncClient.Write(
                                                UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score);

                                            server.SendMessage(syncClient, entry.Value.Connection,
                                                NetDeliveryMethod.ReliableOrdered);
                                        }
                                    }

                                    break;

                                case PacketTypes.CHATSEND:
                                    string messager = inc.ReadString();

                                    Console.WriteLine("{0} : {1}",
                                        UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Name,
                                        messager);

                                    RelayChat(inc.SenderConnection.RemoteUniqueIdentifier, messager);

                                    break;
                            }

                            break;

                        case NetIncomingMessageType.StatusChanged:

                            Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status);

                            if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected ||
                                inc.SenderConnection.Status == NetConnectionStatus.Disconnecting)
                            {
                                UserToConnection.Remove(inc.SenderConnection.RemoteUniqueIdentifier);
                                NetOutgoingMessage outmsg = server.CreateMessage();
                                outmsg.WriteVariableInt64(inc.SenderConnection.RemoteUniqueIdentifier);
                                server.SendToAll(outmsg, NetDeliveryMethod.ReliableOrdered);
                            }
                            break;

                        case NetIncomingMessageType.DiscoveryRequest:
                            NetOutgoingMessage discovermsg = server.CreateMessage();
                            discovermsg.Write("Hey I just met you, I'm a server, so address me maybe");
                            Console.WriteLine("WOW ~NETWORKING~");
                            server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint);
                            break;
                    }
                }
                Thread.Sleep(1);
            }
        }
예제 #6
0
        private static void HandleProtocol(NetIncomingMessage inc, byte packetheader, NetServer server)
        {
            switch ((PacketTypes.Headers) packetheader)
            {
                case PacketTypes.Headers.ReadyUpdate:
                    bool playerStatus = Convert.ToBoolean(inc.ReadString());
                    Player thePlayer = LookUpPlayer(inc.SenderConnection.RemoteUniqueIdentifier);

                    Console.WriteLine("Player {0} changed status to {1}", thePlayer.Name, playerStatus);
                    Players[inc.SenderConnection.RemoteUniqueIdentifier].ToggleReady();
                    NetOutgoingMessage msg = server.CreateMessage();
                    msg.Write((byte) PacketTypes.Headers.ReadyUpdate);
                    msg.Write(inc.SenderConnection.RemoteUniqueIdentifier);
                    msg.Write(playerStatus);
                    server.SendToAll(msg, NetDeliveryMethod.ReliableOrdered);
                    break;
                case PacketTypes.Headers.LoggedIn:
                    string username = inc.ReadString();
                    Player newPlayer = NewPlayer(inc, server, username);
                    Console.WriteLine(Players.Count);
                    if (Players.Count == 0)
                    {
                        Console.WriteLine("Sending {0} host packet", newPlayer.Name);
                        NetOutgoingMessage hMessage = server.CreateMessage();
                        hMessage.Write((byte) PacketTypes.Headers.YouAreHost);
                        server.SendMessage(hMessage, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                    }

                    Players.Add(inc.SenderConnection.RemoteUniqueIdentifier, newPlayer);
                    Players[inc.SenderConnection.RemoteUniqueIdentifier].Connection = inc.SenderConnection;
                    break;
                case PacketTypes.Headers.ChatSend:
                    if (Players[inc.SenderConnection.RemoteUniqueIdentifier].Name != _drawer)
                    {
                        NetOutgoingMessage chatMessageRelay = server.CreateMessage();
                        string chatM = inc.ReadString();
                        chatMessageRelay.Write((byte) PacketTypes.Headers.ChatReceive);
                        chatMessageRelay.Write(Players[inc.SenderConnection.RemoteUniqueIdentifier].Name);
                        chatMessageRelay.Write(chatM);
                        if (!_badwordList.Contains(chatM, StringComparer.OrdinalIgnoreCase))
                        {
                            server.SendToAll(chatMessageRelay, NetDeliveryMethod.ReliableOrdered);
                        }
                        if (String.Equals(chatM, _theWord, StringComparison.CurrentCultureIgnoreCase) & chatM != null)
                        {
                            NetOutgoingMessage someoneOne = server.CreateMessage();
                            someoneOne.Write((byte) PacketTypes.Headers.ChatReceive);
                            someoneOne.Write("Server");
                            someoneOne.Write(Players[inc.SenderConnection.RemoteUniqueIdentifier].Name
                                             + " has guessed the correct word being: " + _theWord);
                            server.SendToAll(someoneOne, NetDeliveryMethod.ReliableOrdered);
                            RoundTimer.Stop();
                            StartNewRound(server);
                        }
                    }
                    break;
                case PacketTypes.Headers.PictureUpdate:
                    int r = inc.ReadVariableInt32();
                    int g = inc.ReadVariableInt32();
                    int b = inc.ReadVariableInt32();
                    int x = inc.ReadVariableInt32();
                    int y = inc.ReadVariableInt32();
                    int size = inc.ReadVariableInt32();
                    NetOutgoingMessage msgPicture = server.CreateMessage();
                    msgPicture.Write((byte) PacketTypes.Headers.PictureUpdate);
                    msgPicture.WriteVariableInt32(r);
                    msgPicture.WriteVariableInt32(g);
                    msgPicture.WriteVariableInt32(b);
                    msgPicture.WriteVariableInt32(x);
                    msgPicture.WriteVariableInt32(y);
                    msgPicture.WriteVariableInt32(size);
                    server.SendToAll(msgPicture, NetDeliveryMethod.ReliableOrdered);
                    break;
                case PacketTypes.Headers.StartGame:
                    NetOutgoingMessage msgStart = server.CreateMessage();
                    msgStart.Write((byte) PacketTypes.Headers.StartGame);
                    server.SendToAll(msgStart, NetDeliveryMethod.ReliableOrdered);
                    RoundTimer.Enabled = true;
                    StartNewRound(server);
                    break;
                case PacketTypes.Headers.DrawLine:
                {
                    int r1 = inc.ReadVariableInt32();
                    int g1 = inc.ReadVariableInt32();
                    int b1 = inc.ReadVariableInt32();
                    int x1 = inc.ReadVariableInt32();
                    int y1 = inc.ReadVariableInt32();
                    int size1 = inc.ReadVariableInt32();
                    int x11 = inc.ReadVariableInt32();
                    int y11 = inc.ReadVariableInt32();
                    NetOutgoingMessage msgDrawLine = server.CreateMessage();
                    msgDrawLine.Write((byte) PacketTypes.Headers.DrawLine);
                    msgDrawLine.WriteVariableInt32(r1);
                    msgDrawLine.WriteVariableInt32(g1);
                    msgDrawLine.WriteVariableInt32(b1);
                    msgDrawLine.WriteVariableInt32(x1);
                    msgDrawLine.WriteVariableInt32(y1);
                    msgDrawLine.WriteVariableInt32(size1);
                    msgDrawLine.WriteVariableInt32(x11);
                    msgDrawLine.WriteVariableInt32(y11);
                    server.SendToAll(msgDrawLine, NetDeliveryMethod.ReliableOrdered);
                }
                    break;
            }
        }
예제 #7
0
        private static void StartNewRound(NetServer server)
        {
            Round theRound = NewRound();
            _drawer = theRound.Drawer.Name;
            _theWord = theRound.Word;
            NetOutgoingMessage newRoundMsg = server.CreateMessage();
            newRoundMsg.Write((byte) PacketTypes.Headers.NewRound);
            newRoundMsg.Write(theRound.Drawer.Name);
            server.SendToAll(newRoundMsg, NetDeliveryMethod.ReliableOrdered);

            NetOutgoingMessage drawerMsg = server.CreateMessage();
            drawerMsg.Write((byte) PacketTypes.Headers.WordMessage);
            drawerMsg.Write(theRound.Word);
            server.SendMessage(drawerMsg, theRound.Drawer.Connection, NetDeliveryMethod.ReliableOrdered);
            _theWord = theRound.Word;
            RoundTimer.Start();
        }