1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using System;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Collections.Generic;
- using NetCoreServer;
- namespace websocketserver.Library
- {
- class ChatServer : WsServer
- {
- List<UserSession> users;
- public ChatServer(IPAddress address, int port) : base(address, port)
- {
- users = new List<UserSession>();
- }
- protected override TcpSession CreateSession()
- {
- UserSession user = new UserSession(this);
- users.Add(user);
- return user;
- }
- public void Subscribe(string key, UserSession session)
- {
- if (session.GetUserKey() == "")
- {
- return;
- }
- GetUsersInChannel(session).ForEach(s => s.SendTextAsync("leave " + session.GetUserKey()));
- session.SetChannel(key);
- var newChannelUsers = GetUsersInChannel(session);
- newChannelUsers.ForEach(s => s.SendTextAsync("join " + session.GetUserKey() + " " + session.GetPosition().X + " " + session.GetPosition().Y));
- session.SendTextAsync("population " + string.Join(" ", newChannelUsers.Select(u => u.GetUserKey() + " " + u.GetPosition().X + " " + u.GetPosition().Y)));
- }
- public void Move(UserSession session)
- {
- if (session.GetUserKey() == "")
- {
- return;
- }
- GetUsersInChannel(session).ForEach(s => s.SendTextAsync("move " + session.GetUserKey() + " " + session.GetPosition().X + " " + session.GetPosition().Y));
- }
- public void Chat(UserSession session, string message)
- {
- if (session.GetUserKey() == "" || message == "")
- {
- return;
- }
- Console.WriteLine("{0} [{1}]: {2}", session.GetUserKey(), session.GetChannel(), message);
- GetUsersInChannel(session).ForEach(s => s.SendTextAsync("chat " + session.GetUserKey() + " " + message));
- }
- public void Disconnect(UserSession session)
- {
- GetUsersInChannel(session).ForEach(s => s.SendTextAsync("leave " + session.GetUserKey()));
- users.Remove(session);
- }
- public List<UserSession> GetUsersInChannel(UserSession session)
- {
- return users.FindAll(u => u.GetUserKey() != "" && u.GetUserKey() != session.GetUserKey() && u.GetChannel() == session.GetChannel());
- }
- public List<UserSession> GetUsersInChannel(string key)
- {
- return users.FindAll(u => u.GetUserKey() != "" && u.GetChannel() == key);
- }
- protected override void OnError(SocketError error)
- {
- Console.WriteLine($"Chat WebSocket server caught an error with code {error}");
- }
- }
- }
|