Ejemplo n.º 1
0
Archivo: Startup.cs Proyecto: sososu/im
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Console.OutputEncoding = Encoding.GetEncoding("GB2312");
            Console.InputEncoding  = Encoding.GetEncoding("GB2312");
            loggerFactory.AddConsole(LogLevel.Error);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseMvc();
            app.UseSwagger().UseSwaggerUI();

            ImHelper.Initialization(new ImClientOptions
            {
                Redis   = new CSRedis.CSRedisClient("127.0.0.1:6379,poolsize=5"),
                Servers = new[] { "127.0.0.1:6001" }
            });

            ImHelper.Instance.OnSend += (s, e) =>
                                        Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");

            ImHelper.EventBus(
                t =>
            {
                Console.WriteLine(t.clientId + "上线了");
                var onlineUids = ImHelper.GetClientListByOnline();
                ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
            },
                t => Console.WriteLine(t.clientId + "下线了"));
        }
Ejemplo n.º 2
0
        public void Configure(IApplicationBuilder app)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Console.OutputEncoding = Encoding.GetEncoding("GB2312");
            Console.InputEncoding  = Encoding.GetEncoding("GB2312");

            app.UseDeveloperExceptionPage();

            app.UseRouting();
            app.UseEndpoints(config => config.MapControllers());
            app.UseDefaultFiles();
            app.UseStaticFiles();

            ImHelper.Initialization(new ImClientOptions
            {
                Redis   = new CSRedis.CSRedisClient("118.25.209.177:26379,idleTimeout=3000,poolsize=5"),
                Servers = new[] { "127.0.0.1:6001" }
            });

            ImHelper.Instance.OnSend += (s, e) =>
                                        Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");

            ImHelper.EventBus(
                t =>
            {
                Console.WriteLine(t.clientId + "上线了");
                var onlineUids = ImHelper.GetClientListByOnline();
                ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
            },
                t => Console.WriteLine(t.clientId + "下线了"));
        }
Ejemplo n.º 3
0
 public object sendmsg([FromForm] Guid senderWebsocketId, [FromForm] Guid receiveWebsocketId, [FromForm] string message, [FromForm] bool isReceipt = false)
 {
     ImHelper.SendMessage(senderWebsocketId, new[] { receiveWebsocketId }, message, isReceipt);
     return(new
     {
         code = 0
     });
 }
Ejemplo n.º 4
0
        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="message"></param>
        public bool HandleMessage(string message, string queenName)
        {
            bool isSuccess = true;

            try
            {
                var(senderClientId, receiveClientId, content, receipt) = JsonConvert.DeserializeObject <(string senderClientId, string[] receiveClientId, string content, bool receipt)>(message as string);
                var outgoing = new ArraySegment <byte>(Encoding.UTF8.GetBytes(content));
                foreach (var clientId in receiveClientId)
                {
                    if (ImServer._clients.TryGetValue(clientId, out var wslist) == false)
                    {
                        //Console.WriteLine($"websocket{clientId} 离线了,{data.content}" + (data.receipt ? "【需回执】" : ""));
                        if (!string.IsNullOrWhiteSpace(senderClientId) && clientId != senderClientId && receipt)
                        {
                            ImHelper.SendMessage(clientId, new[] { senderClientId }, queenName, new
                            {
                                content,
                                receipt = "用户不在线"
                            });
                        }
                        continue;
                    }

                    ImServer.ImServerClient[] sockarray = wslist.Values.ToArray();

                    //如果接收消息人是发送者,并且接收者只有1个以下,则不发送
                    //只有接收者为多端时,才转发消息通知其他端
                    if (clientId == senderClientId && sockarray.Length <= 1)
                    {
                        continue;
                    }

                    foreach (var sh in sockarray)
                    {
                        sh.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
                    }

                    if (string.IsNullOrWhiteSpace(senderClientId) && clientId != senderClientId && receipt)
                    {
                        ImHelper.SendMessage(clientId, new[] { senderClientId }, queenName, new
                        {
                            content,
                            receipt = "发送成功"
                        });
                    }
                    Log.Information(message);
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                Log.Error(message, "发送失败", ex.Message);
            }
            return(isSuccess);
        }
Ejemplo n.º 5
0
        public async Task <AjaxResult <object> > MsgRead([FromForm] Guid from, [FromForm] Guid to)
        {
            await _msgManager.Read(Appid, from.ToString(), to.ToString());

            int ope = -1;

            ImHelper.SendMessage(from, new[] { to }, new { ope, to, from }, false);

            return(new AjaxResult <object>());
        }
Ejemplo n.º 6
0
        public async Task <object> SendMessage([FromBody] Packet packet)
        {
            ApiResult <object> result = new ApiResult <object>();
            var grain = _client.GetGrain <IChatGrain>(packet.SendId);

            var(status, msg) = await ImHelper.SendMessage(packet);

            if (!status)
            {
                result.Code = 1;
            }
            result.Msg  = msg;
            result.Data = new { };
            return(result);
        }
Ejemplo n.º 7
0
        public object sendmsg([FromForm] string senderWebsocketId, [FromForm] string receiveWebsocketId, [FromForm] string message, [FromForm] bool isReceipt = false)
        {
            //var loginUser = 发送者;
            //var recieveUser = User.Get(receiveWebsocketId);

            //if (loginUser.好友 != recieveUser) throw new Exception("不是好友");

            ImHelper.SendMessage(senderWebsocketId, new[] { receiveWebsocketId }, message, isReceipt);

            //loginUser.保存记录(message);
            //recieveUser.保存记录(message);

            return(new
            {
                code = 0
            });
        }
Ejemplo n.º 8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStaticFiles();
            app.UseSwagger().UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
                c.DocExpansion(DocExpansion.None);
            });
            ImHelper.Initialization(new ImClientOptions
            {
                Redis   = new CSRedis.CSRedisClient("127.0.0.1:6379,poolsize=5"),
                Servers = new[] { "127.0.0.1:6001" }
            });


            ImHelper.Instance.OnSend += (s, e) =>
                                        Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");

            ImHelper.EventBus(
                t =>
            {
                Console.WriteLine(t.clientId + "上线了");
                var onlineUids = ImHelper.GetClientListByOnline();
                ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
            },
                t => Console.WriteLine(t.clientId + "下线了"));

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 9
0
        //游戏环节
        public static void SendGameMessage(GamePlay game, Player[] players)
        {
            if (players == null)
            {
                players = redis.HGet <Player[]>($"ddz_gameplay_ht{game.Id}", "players");
            }

            foreach (var player in players)
            {
                ImHelper.SendMessage(Guid.Empty, new[] { player.Id }, new
                {
                    type  = "GamePlay",
                    ddzid = game.Id,
                    data  = game.Data.CloneToPlayer(player.Nick)
                });
            }
        }
Ejemplo n.º 10
0
        public async Task <AjaxResult <object> > SendMsg([FromForm] Guid from, [FromForm] int ope, [FromForm] Guid to, [FromForm] int type, [FromForm] string body, [FromForm] string frominfo)
        {
            //判断是否存在
            if (!await _userManager.CheckAccid(from.ToString(), Appid))
            {
                return(new AjaxResult <object>("消息发送者 不存在"));
            }
            if (ope == 0)
            {
                if (!await _userManager.CheckAccid(to.ToString(), Appid))
                {
                    return(new AjaxResult <object>("用户id 不存在"));
                }
            }
            else if (ope == 1)
            {
                if (!await _channelManager.CheckChannel(to.ToString(), Appid))
                {
                    return(new AjaxResult <object>("群id 不存在"));
                }
            }
            else
            {
                return(new AjaxResult <object>("ope不存在"));
            }

            int id = await _msgManager.Add(Appid, from.ToString(), ope, to.ToString(), type, body);

            //判断自己是否在线
            if (!ImHelper.HasOnline(from))
            {
                return(new AjaxResult <object>("你不在线"));
            }
            //发送消息
            if (ope == 0)//单聊
            {
                ImHelper.SendMessage(from, new[] { to }, new { id, ope, type, to, body, frominfo, from }, true);
            }
            else if (ope == 1)//群聊
            {
                ImHelper.SendChanMessage(from, to.ToString(), new { id, ope, type, to, body, frominfo, from });
            }

            return(new AjaxResult <object>((object)(from + ":" + to)));
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var virtualPath = Configuration["virtualPath"];

            if (env.IsDevelopment())
            {
                virtualPath = "";
                app.UseDeveloperExceptionPage();
            }
            app.UseCors("all");
            //启用中间件服务生成Swagger作为JSON终结点
            app.UseSwagger();
            //启用中间件服务对swagger-ui,指定Swagger JSON终结点
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint(virtualPath + "/swagger/v1/swagger.json", "IM API V1");
            });

            ImHelper.Initialization(new ImClientOptions
            {
                Redis   = new CSRedis.CSRedisClient(Configuration["ImServerOption:CSRedisClient"]),
                Servers = Configuration["ImServerOption:Servers"].Split(";"),//IMsever的地址,外网地址
                WsType  = Configuration["ImServerOption:SslType"]
            });

            ImHelper.Instance.OnSend += (s, e) =>
                                        Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");

            ImHelper.EventBus(
                t =>
            {
                Console.WriteLine(t.clientId + "上线了");
                var onlineUids = ImHelper.GetClientListByOnline();
                ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
            },
                t => Console.WriteLine(t.clientId + "下线了"));

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 12
0
        public IEnumerable <WeatherForecast> Get()
        {
            Commont.LogCommont.SerilogActionExtention.CreateInstance().Info($"时间:{DateTime.Now.ToString()}");
            Commont.LogCommont.SerilogActionExtention.CreateInstance().Debug($"时间:{DateTime.Now.ToString()}");
            Commont.LogCommont.SerilogActionExtention.CreateInstance().Error($"时间:{DateTime.Now.ToString()}");
            Commont.LogCommont.SerilogActionExtention.CreateInstance().Warning($"时间:{DateTime.Now.ToString()}");

            string Ip      = this.Request.Headers["X-Real-IP"].FirstOrDefault() ?? this.Request.HttpContext.Connection.RemoteIpAddress.ToString();
            var    newGuid = Guid.NewGuid();

            ImHelper.JoinChan(Guid.NewGuid(), "demoChan");//群聊,绑定消息频道
            ImHelper.PrevConnectServer(newGuid, Ip);

            ImHelper.GetChanList().Select(a => new { a.chan, a.online });
            var temp2 = Guid.NewGuid();

            for (int i = 0; i < 10; i++)
            {
                var temp = Guid.NewGuid();
                temp2 = temp;
                ImHelper.PrevConnectServer(temp, Ip);
                ImHelper.JoinChan(temp, "demoChan");//群聊,绑定消息频道
            }
            ImHelper.SendChanMessage(newGuid, "demoChan", "hello word");
            ImHelper.SendMessage(newGuid, new[] { temp2 }, " SendMessage hello word ", false);

            var rng = new Random();

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
                   .ToArray());
        }
Ejemplo n.º 13
0
        static DDZGamePlayController()
        {
            ConcurrentDictionary <Guid, (Player, DateTime)> offlineSitdownDic = new ConcurrentDictionary <Guid, (Player, DateTime)>();

            timer = new Timer(state =>
            {
                foreach (var k in offlineSitdownDic.Keys)
                {
                    if (offlineSitdownDic.TryGetValue(k, out var tryval) && DateTime.Now.Subtract(tryval.Item2).TotalSeconds > 4)
                    {
                        try
                        {
                            var ddzid = redis.HGet("ddz_gameplay_player_ht", tryval.Item1.Id.ToString());
                            if (!string.IsNullOrEmpty(ddzid))
                            {
                                var ddz = GamePlay.GetById(ddzid);
                                foreach (var pl in ddz.Data.players)
                                {
                                    if (pl.id == tryval.Item1.Nick)
                                    {
                                        pl.score  = ddz.Data.multiple * (ddz.Data.multipleAddition + ddz.Data.bong) * -2;
                                        pl.status = GamePlayerStatus.逃跑;
                                    }
                                    else
                                    {
                                        pl.score = ddz.Data.multiple * (ddz.Data.multipleAddition + ddz.Data.bong);
                                    }
                                }
                                ddz.Data.stage = GameStage.游戏结束;
                                ddz.SaveData();
                            }
                            StandupStatic(tryval.Item1).Wait();
                        }
                        catch { }
                    }
                }
            }, null, 2000, 2000);

            ImHelper.EventBus(
                t =>
            {
                Console.WriteLine(t.clientId + "上线了");
                try
                {
                    var onlineUids = ImHelper.GetClientListByOnline();
                    ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
                    if (offlineSitdownDic.TryRemove(t.clientId, out var oldval))
                    {
                        var ddzid = redis.HGet("ddz_gameplay_player_ht", t.clientId.ToString());
                        if (!string.IsNullOrEmpty(ddzid))
                        {
                            var ddz    = GamePlay.GetById(ddzid);
                            var player = Player.Find(t.clientId);
                            SendGameMessage(ddz, new[] { player });
                        }
                    }
                }
                catch
                {
                }
            },
                t =>
            {
                Console.WriteLine(t.clientId + "下线了");
                try
                {
                    //用户离线后4秒,才退出座位
                    if (redis.HExists("sitdown_player_ht", t.clientId.ToString()))
                    {
                        var player = Player.Find(t.clientId);
                        if (player != null)
                        {
                            offlineSitdownDic.TryAdd(t.clientId, (player, DateTime.Now));
                        }
                    }
                }
                catch
                {
                }
            });

            GamePlay.OnGameOver        = game => OnGameOver(game);
            GamePlay.OnOperatorTimeout = game => SendGameMessage(game, null);

            redis.Del("sitdown_ht", "sitdown_player_ht");
        }