using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace GameServer { public class User { #region 私有,静态 private static List Users = new List(); //private static ulong counter = 1; #endregion /// /// 用户ID(服务端) /// public ulong userId = 0; /// /// 远程终端节点 /// public string remoteId = ""; /// /// 用户姓名 /// public string username = ""; /// /// 所在房间ID(0表示不在任何房间) /// public ulong roomId = 0; public TcpClient client = null; public NetworkStream stream = null; /// /// 用户构造函数 /// /// 客户端 /// 流 public User(TcpClient _client, NetworkStream _stream) { client = _client; stream = _stream; remoteId = client.Client.RemoteEndPoint.ToString(); Users.Add(this); } /// /// 注册 /// /// 名字 public void Regist(string _username) { userId = ulong.Parse(_username); username = _username; byte[] response = Encoding.UTF8.GetBytes(string.Format("regist {0},{1},{2}", userId, username, roomId)); stream.WriteAsync(response, 0, response.Length); } /// /// 写入 /// /// public void Write(string msg) { byte[] buffer = Encoding.UTF8.GetBytes(msg); stream.WriteAsync(buffer, 0, buffer.Length); } public void OffLine() { Room.LeaveRoom(this); Users.Remove(this); } /// /// 创建用户 /// /// /// public static User Create(TcpClient _client, NetworkStream _stream) { return new User(_client, _stream); } /// /// 获取用户列表 /// /// 除此之外(通常指自己) /// public static string GetUsers(ulong except, ulong roomId = 0) { StringBuilder sb = new StringBuilder(); var tempUsers = Users; if (roomId != 0) { tempUsers = Users.Where(u => u.roomId.Equals(roomId)).ToList(); } tempUsers.ForEach(u => { if (u.userId != except) { sb.AppendFormat("{0},{1},{2};", u.userId, u.username, u.roomId); } }); return sb.ToString().Trim(';'); } public static List GetAllUsers() { return Users; } /// /// 私发 /// /// public static void Send2User(ulong _userId, string msg) { var user = Users.Find(u => u.userId == _userId); if (user != null) { user.Write(msg); } } /// /// 房间 /// /// public static void Send2Room(ulong _userId, ulong _roomId, string msg) { var users = Users.Where(u => u.roomId == _roomId && u.userId != _userId).ToList(); users.ForEach(u => { if (u.roomId != 0) { u.Write(msg); } }); } /// /// 房间 /// /// public static void Send2Player(ulong _userId, ulong _roomId, string msg) { var users = Users.Where(u => u.roomId == _roomId && u.userId != _userId).ToList(); users.ForEach(u => { if (u.roomId != 0) { u.Write(String.Format("{0}", msg)); } }); } /// /// 世界 /// /// public static void Send2World(User _user, string msg) { Users.ForEach((u) => { if (u.userId != _user.userId) u.Write(msg); }); } } }