Last active
August 29, 2015 14:21
-
-
Save gmich/cc0d256b0db04a8d24f5 to your computer and use it in GitHub Desktop.
Gem Network Basic Network Package Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//The network package | |
[NetworkPackage("Chat")] | |
public class Package | |
{ | |
public string Name { get; set; } | |
public string Message { get; set; } | |
} | |
//The chat client | |
private readonly INetworkEvent chatEvent; | |
private readonly GemClient netClient; | |
private readonly nickName; | |
public ChatClient(string nickName) | |
{ | |
this.nickName= nickName; | |
GemNetworkDebugger.Echo = Console.WriteLine; | |
client = new GemClient("GemChat", new ConnectionConfig | |
{ | |
ServerName = "ExampleChat", | |
IPorHost = "127.0.0.1", | |
Port = 14242, | |
DisconnectMessage = "bye" | |
}, | |
PackageConfig.TCP); | |
client.RunAsync(() => new ConnectionApprovalMessage | |
{ | |
Message = "Incoming client", | |
Sender = name, | |
Password = "gem" | |
}); | |
GemClient.Profile("Chat") | |
.OnReceivedServerNotification(notification => Console.WriteLine(notification.Message)); | |
chatEvent= | |
GemClient.Profile("Chat") | |
.CreateNetworkProtocolEvent<Package>() | |
.HandleIncoming((sender, package) => | |
{ | |
Console.WriteLine(String.Format("{0} : {1}", package.Name,package.Message)); | |
}) | |
.GenerateSendEvent(); | |
} | |
public void Chat() | |
{ | |
var msg = Console.ReadLine(); | |
chatEvent(new Package { Name= this.Name, Message = msg } ); | |
} | |
//The chat server | |
private readonly GemServer server; | |
private readonly Dictionary<NetConnection, string> ConnectedPeers = new Dictionary<NetConnection, string>(); | |
public Server() | |
{ | |
gemServer = new GemServer(ActiveProfile, new ServerConfig | |
{ | |
Name = "GemChat", | |
Port = 14242, | |
EnableUPnP = false, | |
MaxConnections = 10, | |
Password = "gem", | |
ConnectionTimeout = 5.0f, | |
MaxConnectionAttempts = 5, | |
RequireAuthentication = true | |
}, | |
PackageConfig.TCP); | |
GemServer.Profile(ActiveProfile).OnIncomingConnection( | |
(server, connection, message) => | |
ConnectedPeers.Add(connection, message.Sender), | |
append: true); | |
GemServer.Profile(ActiveProfile).OnClientDisconnect( | |
(server, connection, message) => | |
ConnectedPeers.Remove(connection), | |
append: true); | |
GemServer.RegisterCommand("whoison", "Show the connected clients by name", false, | |
(server, sender, command, arguments) => | |
{ | |
server.NotifyOnly(String.Join(Environment.NewLine, ConnectedPeers.Select(x => x.Value)), sender); | |
}); | |
gemServer.RunAsync(); | |
while (true) GemServer.ExecuteCommand(Console.ReadLine()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment