/// <summary> /// Initializes a new instance of the <see cref="Client"/> class. /// The client. /// </summary> /// <param name="srvr"> /// </param> public Client(ChatServer srvr) : base(srvr) { this.Character = new Character(0, null); this.ServerSalt = string.Empty; this.knownClients = new List<uint>(); }
protected override void OnStart(string[] args) { Status("", true); Status("The ChatServer is initializing...", true); //log service initializing _port = SelectServerPort(); Status("Done SelectServerPort...", true); //_server = ChatServer.Factory(_port); //_backgroundThread = new Thread(new ThreadStart(this.RunServer)); //_backgroundThread.Start(); //LogApplicationEvent("Start", "The ChatServer has successfully started up on port " + _port); LifetimeServices.LeaseTime = TimeSpan.FromDays(365); LifetimeServices.RenewOnCallTime = TimeSpan.FromDays(365); //Set up the channel details BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider(); provider.TypeFilterLevel = TypeFilterLevel.Full; Status("Done BinaryServerFormatterSinkProvider...", true); string address = ChatServer.ChatServerIp;// ChatServer.GetMyIP(); Hashtable props = new Hashtable(); props.Add("port", _port); props.Add("bindTo", address); props.Add("name", "Address:" + address + ":" + _port);//this needs to be unique Status("Init on address:" + address + ":" + _port, true); //Create the channel TcpServerChannel chan = new TcpServerChannel(props, provider); Status("Done TcpServerChannel...", true); //register it ChannelServices.RegisterChannel(chan, false); Status("Done RegisterChannel", true); //register the object as a service RemotingConfiguration.RegisterWellKnownServiceType(typeof(ChatServer), "Reg", WellKnownObjectMode.Singleton); Status("Done RegisterWellKnownType", true); _server = new ChatServer(new ChatServer.StatusDelegate(Status)); Status("Done ChatServer...", true); RemotingServices.Marshal(_server, "Reg"); Status("Done RemotingServices.Marshal...", true); //_server.Setup(_port); Status("Done Setup...", true); _backgroundThread = new Thread(new ThreadStart(this.RunServer)); _backgroundThread.Start(); Status("Done Start...", true); //LogApplicationEvent("Start", "The ChatServer has successfully started up on port " + _port); }
public InterpolatorScene(ISceneHost scene) { _scene = scene; _log = _scene.GetComponent<ILogger>(); _env = _scene.GetComponent<IEnvironment>(); Chat = ChatServerExtensions.AddChat(_scene); replicator.Init(_scene); }
private void button1_Click(object sender, EventArgs e) { // Parse the server's IP address out of the TextBox IPAddress ipAddr = IPAddress.Parse(txtIp.Text); // Create a new instance of the ChatServer object ChatServer mainServer = new ChatServer(ipAddr); // Hook the StatusChanged event handler to mainServer_StatusChanged ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged); // Start listening for connections mainServer.StartListening(); // Show that we started to listen for connections txtLog.AppendText("Monitoring for connections...\r\n"); }
public void Run() { try { exitCode = ExitCode.ErrorServerNotStarted; ConsoleSampleServer().Wait(); Console.WriteLine("Server started. Press Ctrl-C to exit..."); exitCode = ExitCode.ErrorServerRunning; } catch (Exception ex) { Utils.Trace("ServiceResultException:" + ex.Message); Console.WriteLine("Exception: {0}", ex.Message); exitCode = ExitCode.ErrorServerException; return; } ManualResetEvent quitEvent = new ManualResetEvent(false); try { Console.CancelKeyPress += (sender, eArgs) => { quitEvent.Set(); eArgs.Cancel = true; }; } catch { } // wait for timeout or Ctrl-C quitEvent.WaitOne(serverRunTime); if (server != null) { Console.WriteLine("Server stopped. Waiting for exit..."); using (ChatServer _server = server) { // Stop status thread server = null; status.Wait(); // Stop server and dispose _server.Stop(); } } exitCode = ExitCode.Ok; }
public JsonResult GetUserInfo(int userId) { var roomId = this.GetMyRoomId(); Debug.Assert(ChatServer.RoomExists(roomId), "user room should be created when user joins the chat"); // this will intentionally trigger an error in case the user doesn't exist. // the client must treat this scenario return(this.Json( new { User = ChatServer.Rooms[roomId].UserExists(userId) ? ChatServer.Rooms[roomId].UsersById[userId] : null }, JsonRequestBehavior.AllowGet)); }
public static void Main() { ChatServer chat = new ChatServer("MSN Chat Room"); // Register to receive event notifications from the server chat.Join += new JoinHandler(OnJoinChat); chat.Quit += new QuitHandler(OnQuitChat); // Call methods on the server chat.JoinChat("Michael"); chat.JoinChat("Bob"); chat.JoinChat("Sam"); chat.ShowMembers("After 3 have joined"); chat.QuitChat("Bob"); chat.ShowMembers("After 1 has quit"); }
public void Should_Check_If_User_Is_Connected_True() { //arrange var server = new ChatServer(); var user = new User(String.Empty); server.Users.Add(user); server.Connect(user); //act var result = server.IsConnected(user); //assert result.ShouldBeEquivalentTo(true); }
public void Should_Disconnect_From_Chat_Server() { //arrange var user = new User(string.Empty); var server = new ChatServer(); server.Users.Add(user); server.Connect(user); //act server.Disconnect(user); //assert user.IsConnected.ShouldBeEquivalentTo(false); }
public JabbrAdapter(ChatServer chatServerConfig) { serverConfig = chatServerConfig; client = new JabbRClient(serverConfig.ServerAddress) { AutoReconnect = true }; Messages = Observable.FromEvent <Action <Message, string>, ChatMessage>(handler => { Action <Message, string> converter = (jabbrMessage, room) => { try { if (client == null) { return; } // Don't relay our own messages if (jabbrMessage.User.Name.Equals(serverConfig.UserName, StringComparison.OrdinalIgnoreCase)) { return; } var chatMessage = new ChatMessage { ServerId = serverConfig.ServerId, Room = room, User = jabbrMessage.User.Name, Text = jabbrMessage.Content, TimeStamp = jabbrMessage.When }; handler(chatMessage); } catch (Exception ex) { Console.WriteLine($"{serverConfig.ServerId}|EXCEPTION: {ex}"); } }; return(converter); }, converter => client.MessageReceived += converter, converter => client.MessageReceived -= converter ); }
public override Response Handle(ChatServer server, Request request) { int nameLength = User.Client.ReceiveInt(Constants.NAME_LENGTH_SEGMENT); string name = User.Client.ReceiveString(nameLength); string password = User.Client.ReceiveString(request.Length - Constants.NAME_LENGTH_SEGMENT - nameLength); if (!Manager.Register(name, password)) { return(new ErrorResponse(new UserAlreadyExistsException())); } User.Id = Manager.GetId(name); User.Name = name; server.AddUser(User); return(new RegisterResponse(User)); }
// TO DO: // Add event handlers for joining and quitting // Display the sender and the name of person public static void Main() { ChatServer chat = new ChatServer(); // Register to receive event notifications from the server // TO DO: // Add code to register your event handlers // Call methods on the server chat.JoinChat("Michael"); chat.JoinChat("Bob"); chat.JoinChat("Sam"); chat.ShowMembers("After 3 have joined"); chat.QuitChat("Bob"); chat.ShowMembers("After 1 has quit"); }
private static void Main() { var address = Dns.GetHostAddresses(Dns.GetHostName()) .Where(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork) .Select(ipAddress => new IPEndPoint(ipAddress, 23000)) .First(); Task.Run(() => ChatServer.StartAsync(address)); ChatServer.ClientConnects.Subscribe(Console.WriteLine); ChatServer.ClientDisconects.Subscribe(Console.WriteLine); ChatServer.ClientMessage.Subscribe(Console.WriteLine); ChatServer.ClientRegistered.Subscribe(Console.WriteLine); Console.WriteLine($"Listening on {address}"); Console.WriteLine("Press enter to kill the server"); Console.ReadLine(); }
public void HostButton() { try { ChatServer s = Instantiate(server).GetComponent <ChatServer>(); s.Init(); ChatClient c = Instantiate(client).GetComponent <ChatClient>(); c.ConnectToServer("127.0.0.1", 6321); } catch (Exception e) { Debug.Log(e.Message); throw; } }
public JsonResult SendTypingSignal(int otherUserId) { var roomId = this.GetMyRoomId(); var myUserId = this.GetMyUserId(this.Request); Debug.Assert(ChatServer.RoomExists(roomId), "user room should be created when user joins the chat"); if (myUserId == otherUserId) { throw new Exception("Cannot send a typing signal to yourself"); } ChatServer.Rooms[roomId].SendTypingSignal(myUserId, otherUserId); return(null); }
public static void Main() { ChatServer server = new ChatServer(1341); //server.start(); ChatClient client = new ChatClient("144.118.118.68", 1341); MessageRecievedListener mrl = delegate(string s) { Console.WriteLine(s); }; client.start(mrl); Console.WriteLine("Type your text:"); while (true) { client.send(Console.ReadLine()); } }
public JsonResult GetMessageHistory(int otherUserId, long?timeStamp = null) { var roomId = this.GetMyRoomId(); var myUserId = this.GetMyUserId(this.Request); Debug.Assert(ChatServer.RoomExists(roomId), "user room should be created when user joins the chat"); // Each UserFrom Id has a LIST of messages. Of course // all messages have the same UserTo, of course, myUserId. var messages = ChatServer.Rooms[roomId].GetMessagesBetween(myUserId, otherUserId, timeStamp); return(this.Json(new { Messages = messages, Timestamp = DateTime.UtcNow.Ticks.ToString() }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Asynchronously creates a new client and starts its connection to the game servers /// </summary> public void Start() { chatServer = new ChatServer(settings, settings.BotNames[ClientIndex]); realmServer = new RealmServer(settings, settings.BotNames[ClientIndex]); gameServer = new GameServer(settings, settings.BotNames[ClientIndex]); chatServerThread = new Thread(() => { chatServer.Run(null); }); realmServerThread = new Thread((args) => { realmServer.Run(args); }); gameServerThread = new Thread((args) => { gameServer.Run(args); }); // Named threads for debugging purposes only chatServerThread.Name = "CHAT:" + CharacterName; realmServerThread.Name = "REALM:" + CharacterName; gameServerThread.Name = "GAME:" + CharacterName; chatServerThread.IsBackground = true; realmServerThread.IsBackground = true; gameServerThread.IsBackground = true; chatServer.ReadyToConnectToRealmServer += new EventHandler <RealmServerArgs>(chatServer_ReadyToConnectToRealmServer); chatServer.OnFailure += new EventHandler <FailureArgs>(chatServer_OnFailure); realmServer.ReadyToConnectToGameServer += new EventHandler <GameServerArgs>(realmServer_ReadyToConnectToGameServer); realmServer.OnDisconnect += new EventHandler(realmServer_OnDisconnect); realmServer.OnFailure += new EventHandler <FailureArgs>(realmServer_OnFailure); gameServer.OnEnterGame += new EventHandler(gameServer_OnEnterGame); gameServer.OnDisconnect += new EventHandler(gameServer_OnDisconnect); gameServer.OnFailure += new EventHandler <FailureArgs>(gameServer_OnFailure); gameServer.OnPlayerCountChanged += new EventHandler <PlayerCountArgs>(gameClient_OnPlayerCountChanged); gameServer.OnShutdown += new EventHandler(gameServer_OnShutdown); IsRunning = true; chatServerThread.Start(); }
private void StopServer() { Server.StopServer(); Server = null; (this as IController).ServerStateChanged(Utils.ServerState.STOPED); ServerStarted = false; ServerIPAddress.IsReadOnly = false; ServerIPPort.IsReadOnly = false; GroupInfoRootPath.IsReadOnly = false; ChatRootPath.IsReadOnly = false; GroupSelectButton.IsEnabled = true; ChatSelectButton.IsEnabled = true; StartServerButton.Content = "启动服务"; }
/// <summary> /// The main entry point for the application. /// </summary> /// <param name="args">The arguments. </param> internal static void Main(string[] args) { // todo: create with HostBuilder var loggerFactory = new NullLoggerFactory().AddLog4Net(Log4NetConfigFilePath, true); logger = loggerFactory.CreateLogger <Program>(); var addressResolver = IpAddressResolverFactory.DetermineIpResolver(args, loggerFactory); var settings = new Settings("ChatServer.cfg"); var serviceContainer = new ServiceContainer(); serviceContainer.AddService(typeof(ILoggerFactory), loggerFactory); int chatServerListenerPort = settings.ChatServerListenerPort ?? 55980; int exDbPort = settings.ExDbPort ?? 55906; string exDbHost = settings.ExDbHost ?? "127.0.0.1"; try { // To make the chat server use our configured encryption key, we need to trick a bit. We add an endpoint with a special client version which is defined in the plugin. var configuration = new ChatServerSettings(); configuration.Endpoints.Add(new ChatServerEndpoint { ClientVersion = ConfigurableNetworkEncryptionPlugIn.Version, NetworkPort = chatServerListenerPort }); var pluginManager = new PlugInManager(null, loggerFactory, serviceContainer); pluginManager.DiscoverAndRegisterPlugInsOf <INetworkEncryptionFactoryPlugIn>(); var chatServer = new ChatServer(configuration, addressResolver, loggerFactory, pluginManager); chatServer.Start(); var exDbClient = new ExDbClient(exDbHost, exDbPort, chatServer, chatServerListenerPort, loggerFactory); logger.LogInformation("ChatServer started and ready"); while (Console.ReadLine() != "exit") { // keep application running } exDbClient.Disconnect(); chatServer.Shutdown(); } catch (Exception ex) { logger.LogCritical(ex, "Unexpected error occured"); } }
public LoginPageViewModel() { server = new ChatServer(); //CreateCommand = new Command(CreateFunction); CreateCommand = new Command(async() => await Shell.Current.Navigation.PushPopupAsync(new InfoPopup("The description", "The message"))); database = new MobileUserDB(); CheckUserCommand = new Command(CheckUser); CreateAccount = new Command(async() => { try { await Shell.Current.Navigation.PushModalAsync(new RegisterPageView()); }catch (Exception ex) { await App.Current.MainPage.Navigation.PushModalAsync(new RegisterPageView()); Console.WriteLine(""); Console.WriteLine(ex.Message); } }); }
/// <summary> /// Runs the chat. /// </summary> private void RunChat() { try { while (true) { var line = this.reader?.ReadLine(); if (!string.IsNullOrWhiteSpace(this.nickName) && !string.IsNullOrWhiteSpace(line)) { ChatServer.SendMsgToAll(this.nickName, line); } } } catch (Exception ex) { Console.WriteLine(ex); } }
private void tb_Toggled(object sender, RoutedEventArgs e) { if (tsStartStop.IsOn) { // validate the port number try { portNumber = int.Parse(tbPortNumber.Text); server = new ChatServer(portNumber, cbInterfaces.SelectedItem, tbServerName.Text); server.ClientConnected += ServerOnClientConnected; server.ClientDisconnected += ServerOnClientDisconnected; var serverName = tbServerName.Text; if (string.IsNullOrWhiteSpace(serverName)) { ShowError(); } else { server.StartServer(); timer.StartTimer(); SetControls(false); } } catch { ShowError(); } } else { if (server == null) { return; } timer.StopTimer(); server.StopServer(); SetControls(true); } }
public static void Initialize(IGameLogger logger, string connectionString, string database, IPEndPoint gameServerConfiguration, IPEndPoint policyServerConfiguration, IPEndPoint chatServerConfiguration) { lock (_lock) { if (_initialized || !(_initialized = true)) { return; } _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _database = new DatabaseContext(connectionString, database); _lookupBuilder = new NettyLookupBuilder(); _gameServer = new GameServer(gameServerConfiguration); _policyServer = new PolicyServer(policyServerConfiguration); _chatServer = new ChatServer(chatServerConfiguration); } }
public bool Login(ChatServer server, string alias = "", string uid = "") { try { Utils.DebugLogger("Chat server: " + server.Name); Utils.DebugLogger("... host: " + server.Host); Utils.DebugLogger("... port: " + server.Port.ToString()); Utils.DebugLogger("... alias: " + alias); Utils.DebugLogger("... UID: " + uid); this.CurrentUserAlias = alias; this.CurrentUserID = uid; lock (this.locker) { this.CurrentServer = server; this.chat_client = new TcpClient(); this.chat_client.Connect(this.CurrentServer.Host, this.CurrentServer.Port); this.Login_Packet(this.CurrentUserAlias, this.CurrentUserID); if (!this.chat_client.Connected) return false; } ThreadStart tsHeartbeat = new ThreadStart(Thread_DoHeartbeat); this.trdHeartbeat = new Thread(tsHeartbeat); this.trdHeartbeat.IsBackground = true; this.trdHeartbeat.Start(); ThreadStart tsDataReceiver = new ThreadStart(Thread_DataReceiver); this.trdDataReceiver = new Thread(tsDataReceiver); this.trdDataReceiver.IsBackground = true; this.trdDataReceiver.Start(); return true; } catch { } return false; }
public void DenyHandler(ChatServer service, ChatSession session, CDenyChatReqMessage message) { var server = service.GameServer; var plr = session.Player; if (message.Deny.AccountId == plr.Account.Id) { return; } Deny deny; switch (message.Action) { case DenyAction.Add: if (plr.DenyManager.Contains(message.Deny.AccountId)) { return; } var target = server.PlayerManager[message.Deny.AccountId]; if (target == null) { return; } deny = plr.DenyManager.Add(target); session.Send(new SDenyChatAckMessage(0, DenyAction.Add, deny.Map <Deny, DenyDto>())); break; case DenyAction.Remove: deny = plr.DenyManager[message.Deny.AccountId]; if (deny == null) { return; } plr.DenyManager.Remove(message.Deny.AccountId); session.Send(new SDenyChatAckMessage(0, DenyAction.Remove, deny.Map <Deny, DenyDto>())); break; } }
public RegisterPageViewModel() { BackCommand = new Command(async() => { try { await Shell.Current.Navigation.PopModalAsync(); }catch (Exception ex) { await App.Current.MainPage.Navigation.PopModalAsync(); } }); RegisterCommand = new Command(RegisterFunction); //RegisterCommand = new Command(async()=>await Shell.Current.Navigation.PushPopupAsync(new InfoPopup())); EmailError = false; UsernameError = false; PasswordError = false; ConfirmPasswordError = false; server = new ChatServer(); ErrorList = new ObservableCollection <string>(); database = new MobileUserDB(); }
public WaitHandle Start() { ConcentratorServer ConcentratorServer = null; ProvisioningClient ProvisioningClient = null; if (Types.TryGetModuleParameter("Concentrator", out object Obj)) { ConcentratorServer = Obj as ConcentratorServer; } if (Types.TryGetModuleParameter("Provisioning", out Obj)) { ProvisioningClient = Obj as ProvisioningClient; } this.bobClient = new BobClient(Gateway.XmppClient, Path.Combine(Gateway.AppDataFolder, "BoB")); this.chatServer = new ChatServer(Gateway.XmppClient, this.bobClient, ConcentratorServer, ProvisioningClient); return(null); }
/// <summary> /// </summary> /// <param name="chatServer"> /// </param> public void Run(ChatServer chatServer) { this.Run(); if (Config.Instance.CurrentConfig.UseIRCRelay) { // Find ingame channel to relay string temp = Config.Instance.CurrentConfig.RelayIngameChannel; this.RelayedChannel = chatServer.Channels.FirstOrDefault(x => x.ChannelName == temp); if (this.RelayedChannel == null) { LogUtil.Debug(DebugInfoDetail.Engine, "Could not find ChatEngine Channel '" + temp + "'"); return; } this.RelayedChannel.OnChannelMessage += this.RelayedChannel_OnChannelMessage; // Found ingame channel, now connect to IRC this.Connect(Config.Instance.CurrentConfig.IRCServer, this.RegistrationInfo); } }
public async Task Chat_LoginHandler(ChatServer server, ChatSession session, Message.Chat.CLoginReqMessage message) { Logger.ForAccount(message.AccountId, "") .Information("Login from {remoteEndPoint}", session.RemoteEndPoint); uint sessionId; if (!uint.TryParse(message.SessionId, out sessionId)) { Logger.ForAccount(message.AccountId, "") .Error("Invalid sessionId"); session.SendAsync(new Message.Chat.SLoginAckMessage(2)); return; } var plr = GameServer.Instance.PlayerManager[message.AccountId]; if (plr == null) { Logger.ForAccount(message.AccountId, "") .Error("Login failed"); session.SendAsync(new Message.Chat.SLoginAckMessage(3)); return; } if (plr.ChatSession != null) { Logger.ForAccount(session) .Error("Already online"); session.SendAsync(new Message.Chat.SLoginAckMessage(4)); return; } session.GameSession = plr.Session; plr.ChatSession = session; Logger.ForAccount(session) .Information("Login success"); session.SendAsync(new Message.Chat.SLoginAckMessage(0)); session.SendAsync(new Message.Chat.SDenyChatListAckMessage(plr.DenyManager.Select(d => d.Map <Deny, DenyDto>()).ToArray())); }
public override Response Handle(ChatServer server, Request request) { int id = User.Client.ReceiveInt(Constants.ID_SEGMNET); if (!Manager.UserExists(id)) { return(new ErrorResponse(new UserNotFoundException())); } string password = User.Client.ReceiveString(request.Length - Constants.ID_SEGMNET); if (!password.Equals(Manager.GetHashedPassword(id))) { return(new ErrorResponse(new WrongPasswordException())); } User.Id = id; User.Name = Manager.GetName(id); server.AddUser(User); return(new LoginResponse(User)); }
public override void ClientConnect(PhotonClientPeer clientPeer) { if (clientPeer.ClientData <CharacterData>().CharacterId.HasValue) { var para = new Dictionary <byte, object> { { (byte)ClientParameterCode.CharacterId, clientPeer.ClientData <CharacterData>().CharacterId.Value }, { (byte)ClientParameterCode.PeerId, clientPeer.PeerId.ToByteArray() } }; if (ChatServer != null) { ChatServer.SendEvent(new EventData((byte)ServerEventCode.CharacterRegister, para), new SendParameters()); } if (clientPeer.CurrentServer != null) { clientPeer.CurrentServer.SendEvent(new EventData((byte)ServerEventCode.CharacterRegister, para), new SendParameters()); } } }
private static void Do_login(ChatServer server, String[] st) { try { String name = st[1]; String pwd = st[2]; server.login(name, pwd); Console.WriteLine("login successful"); } catch (org.apache.etch.examples.chat.types.Chat.Failure e) { Console.WriteLine("failed : " + e.GetMessage()); } catch (IndexOutOfRangeException) { Console.WriteLine("usage : login <username> <pwd>"); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); this.subscription?.Unsubscribe(); this.subscription = null; this.registryClient?.Dispose(); this.registryClient = null; this.chatServer?.Dispose(); this.chatServer = null; this.bobClient?.Dispose(); this.bobClient = null; this.sensorServer?.Dispose(); this.sensorServer = null; this.sensorClient?.Dispose(); this.sensorClient = null; this.controlClient?.Dispose(); this.controlClient = null; this.xmppClient?.Dispose(); this.xmppClient = null; this.secondTimer?.Dispose(); this.secondTimer = null; db?.Stop()?.Wait(); db?.Flush()?.Wait(); Log.Terminate(); deferral.Complete(); }
public override void ClientDisconnect(PhotonClientPeer clientPeer) { //Log.DebugFormat("Trying to disconnect client {0}:{1}", clientPeer.PeerId, clientPeer.ClientData<CharacterData>().CharacterId.Value); var para = new Dictionary <byte, object> { { (byte)ClientParameterCode.PeerId, clientPeer.PeerId.ToByteArray() } }; if (clientPeer.ClientData <CharacterData>().CharacterId.HasValue) { Log.DebugFormat("Sending disconnect for client {0}:{1}", clientPeer.PeerId, clientPeer.ClientData <CharacterData>().CharacterId.Value); if (ChatServer != null) { ChatServer.SendEvent(new EventData((byte)ServerEventCode.CharacterDeregister, para), new SendParameters()); } if (clientPeer.CurrentServer != null) { clientPeer.CurrentServer.SendEvent(new EventData((byte)ServerEventCode.CharacterDeregister, para), new SendParameters()); } } LoginServer.SendEvent(new EventData((byte)ServerEventCode.UserLoggedOut, para), new SendParameters()); }
private void cbStartStop_Checked(object sender, RoutedEventArgs e) { if (cbStartStop.IsChecked == true) { // validate the port number try { var port = Int32.Parse(tbPortNumber.Text); server = new ChatServer(port, cbInterfaces.SelectedItem, tbServerName.Text); server.ClientConnected += ServerOnClientConnected; server.ClientDisconnected += ServerOnClientDisconnected; var serverName = tbServerName.Text; if (string.IsNullOrWhiteSpace(serverName)) { ShowError(); } else { server.StartServer(); SetControls(false); } } catch { ShowError(); } } else { if (server == null) return; server.StopServer(); SetControls(true); } }
static void Main(string[] args) { var connectionFactory = new DefaultConnectionFactory("localhost"); using(var connection = connectionFactory.CreateConnection()) { var model = connection.CreateModel(); model.ExchangeDeclare("RabbusChat", ExchangeType.Topic, false); } var consumerContainer = new SimpleConsumerContainer(); var bus = new RogerBus(connectionFactory, consumerContainer, exchangeResolver: new StaticExchangeResolver("RabbusChat")); var chat = new ChatServer(bus); consumerContainer.Register(chat); bus.Start(); Console.ReadLine(); bus.Dispose(); }
void registerMe(String nick, String _port) { try { _nick = nick; int port = Int32.Parse(_port); TcpChannel channel = new TcpChannel(port); ChannelServices.RegisterChannel(channel, false); server = (ChatServer)Activator.GetObject( typeof(ChatServer), "tcp://localhost:8086/ChatServer" ); ChatClient obj = (ChatClient)Activator.GetObject( typeof(ChatClient), "tcp://localhost:8086/ChatClient"); //pass the object here, so we keep a reference that link us to the UI rmc = new RemoteChatClient(this); String clientServiceName = "ChatClient"; RemotingServices.Marshal( rmc, clientServiceName, typeof(RemoteChatClient) ); if (server != null) { server.register(nick, "tcp://localhost:" + port + "/" + clientServiceName); isConnected = true; } } catch (SocketException) { System.Windows.Forms.MessageBox.Show("Could not locate server"); } catch (FormatException e) { System.Windows.Forms.MessageBox.Show("Invalid format port"); } catch (RemotingException e) { System.Console.WriteLine(e); } }
protected override void OnStop() { Status("Stopping...", true); LogApplicationEvent("Closing", "The ChatServer is shutting down"); //Save state to DB //Set ChatServer as inactive //Remove entry from database //_server.UnRegisterSelfOnDatabase(); //stop running try { _backgroundThread.Abort(); } catch(Exception ex) { Status("Problem aborting the garbage collector background thread\n" + ex.ToString(), true); LogApplicationEvent("Stop", "Problem aborting the garbage collector background thread\n"+ex.ToString()); } _server.Active = false; _server = null; LogApplicationEvent("Stop", "The ChatServer has successfully stopped"); Status("Stopped...", true); Status("", true); }
/// <summary> /// </summary> /// <param name="chatServer"> /// </param> public void Run(ChatServer chatServer) { this.Run(); if (Config.Instance.CurrentConfig.UseIRCRelay) { // Find ingame channel to relay string temp = Config.Instance.CurrentConfig.RelayIngameChannel; this.RelayedChannel = chatServer.Channels.Where(x => x.ChannelName == temp).FirstOrDefault(); if (this.RelayedChannel == null) { LogUtil.Debug("Could not find ChatEngine Channel '" + temp + "'"); return; } this.RelayedChannel.OnChannelMessage += this.RelayedChannel_OnChannelMessage; // Found ingame channel, now connect to IRC this.Connect(Config.Instance.CurrentConfig.IRCServer, this.RegistrationInfo); } }
public void serverMode() { ChatServer server = null; try { server = new ChatServer(); Console.WriteLine("SyncChat Server started on " + NetworkInfo.IpString + ":" + NetworkInfo.portString); Console.WriteLine("Awaiting Connection..."); if (server.startServer()) Console.WriteLine("Client Connected!"); this.fancyOutput(); server.sendMessage("Welcome to the server"); while (true) { if (Console.KeyAvailable) { if (Console.ReadKey(true).Key == ConsoleKey.I) { Console.Write(">> "); this.data = Console.ReadLine(); server.sendMessage(this.data); if (this.data.ToLower().Equals("quit")) { server.close(); Console.WriteLine("Server Closed!"); break; } } } else if (server.messageAvailable()) { this.data = server.getData(); if (this.data.ToLower().Equals("quit")) { server.close(); Console.WriteLine("Server Closed!"); break; } else Console.WriteLine("Client: {0}", this.data); } } } catch (System.Net.Sockets.SocketException) { Console.WriteLine("A Server is already running!"); } catch (System.IO.IOException) { Console.WriteLine("All Clients have left! - Exiting"); server.close(); } }