void OnConnect(IAsyncResult ar) { SocketClient client = ar.AsyncState as SocketClient; SocketEntity socketEnt = client.socket; Socket socket = socketEnt.socket; try { socket.EndConnect(ar); socketEnt.offset = 0; socketEnt.packet = 0; socket.BeginReceive(socketEnt.buffer.buffer, socketEnt.buffer.writePosition, socketEnt.buffer.writeLength, SocketFlags.None, new AsyncCallback(this.OnReceive), client); socketEnt.postSend(); SocketEvent e = new SocketEvent(); e.name = SocketEvent.CONNECT; dispatchEvent(socketEnt, e); } catch (SocketException ex) { SocketEvent e = new SocketEvent(); e.name = SocketEvent.EXCEPTION; e.data = System.Text.Encoding.Default.GetBytes(ex.Message); dispatchEvent(socketEnt, e); } }
/// <summary> /// 处理前端传来的信息判断要执行什么操作 /// </summary> /// <param name="astrMessage">信息</param> /// <param name="aobjSocketSession">websocket连接Session</param> public void handlerMessage(string astrMessage, WebSocketSession aobjSocketSession) { SocketEntity socketEntity = JsonConvert.DeserializeObject <SocketEntity>(astrMessage); System.Diagnostics.Debug.WriteLine(socketEntity); SocketEnum socketEnum = (SocketEnum)Enum.Parse(typeof(SocketEnum), socketEntity.Tag); System.Diagnostics.Debug.WriteLine(socketEnum); switch (socketEnum) { case SocketEnum.ac: handlerControllerAction(socketEntity, aobjSocketSession); break; case SocketEnum.c: updateSessionKey(socketEntity, aobjSocketSession); break; case SocketEnum.i: InRoom(socketEntity); break; case SocketEnum.q: break; } }
/// <summary> /// 发送到服务 /// </summary> /// <param name="msg"></param> public void SendMessage(SocketEntity msmqEntity) { try { if (msmqEntity == null) { return; } if (SocketHelper.IsSocketConnected_Poll(socket)) { string strmsg = JSONSerialize.JsonSerialize_Newtonsoft(msmqEntity); byte[] data = Encoding.UTF8.GetBytes(SocketHelper.SocketMsgSplit + strmsg + SocketHelper.SocketMsgSplit); socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), socket); OnSockConnEvent(new SocketStatusEventArgs(true)); } else { Connect(); } } catch (Exception ex) { logger.ErrorException("SendMessage", ex); } }
void OnMessageHandler(object sender, MessageEventArgs e) { string message = "Charts WebSocket server said: " + e.Data; Debug.Log(message); string jsonString = System.Text.Encoding.UTF8.GetString(e.RawData); SocketEntity entity = JsonUtility.FromJson <SocketEntity>(jsonString); string teamId = entity.data.tid + ""; string shotType = entity.data.st; if (shotType != null && !shotType.IsNullOrEmpty()) { UnityMainThreadDispatcher.Instance().Enqueue(() => { if (shotType.Equals("MAKE") && OnMake != null) { OnMake(teamId); } else if (shotType.Equals("MISS") && OnMiss != null) { OnMiss(teamId); } }); } }
private void BuildServices(IServiceCollection services) { Global.Client = new DiscordSocketClient(SocketEntity.GetDefault()); Global.WebClient = OriWebClient.Default; services .AddSingleton <DataContainer>() //.AddSingleton(new LockedDblWrapper()) //.AddSingleton(new DiscordShardedClient(new int[] {0}, SocketEntity.GetDefault())) .AddSingleton(new DiscordSocketClient(SocketEntity.GetDefault())) .AddSingleton(new CommandService(CommandEntity.GetDefault())) .AddSingleton(new AudioDependency()) .AddSingleton(new CancellationTokenSource()) .AddSingleton <DynamicManager>() //.AddSingleton<EventDependency>() .AddSingleton <NetworkManager>() .AddSingleton <ConsoleDependency>() .AddSingleton <AudioService>() .AddSingleton <InsultService>() .AddSingleton <StatusService>() .AddSingleton <GuildPrefUtility>() .AddSingleton <Exceptions>() //.AddSingleton<EventLogger>() .AddSingleton <Random>() .AddSingleton(Configuration); }
private void UniversalTerParm_Load(object sender, EventArgs e) { //是否启用招测 calldataEnable = Settings.Instance.GetBool(SettingKeys.CallDataEnable); GridColumn calldataCol = gridViewTer.Columns["OnLinePic"]; calldataCol.Visible = calldataEnable; InitGrid(); if (calldataEnable) { //获取终端在线状态 SocketEntity msmqEntity = new SocketEntity(); msmqEntity.MsgType = ConstValue.MSMQTYPE.Get_OnLineState; GlobalValue.SocketMgr.SendMessage(msmqEntity); } #region /* * ceCallData.CheckedChanged += new EventHandler(ceCallData_CheckedChanged); * ImageList imageList = new ImageList(); * imageList.ImageSize = new System.Drawing.Size(12, 12); * imageList.ColorDepth = ColorDepth.Depth32Bit; * imageList.Images.Add(SmartWaterSystem.Properties.Resources.灭灯16x25); * imageList.Images.Add(SmartWaterSystem.Properties.Resources.亮灯16x25); * string[] s = new string[] { "关","开"}; * for (int i = 0; i < s.Length; i++) * ImageComboBox_Online.Items.Add(new ImageComboBoxItem(s[i], i, i)); * * this.ImageComboBox_Online.SmallImages = imageList; * */ #endregion }
private void buttonServerStart_Click(object sender, EventArgs e) { //_server = SocketEntity.Create((int)this.numericUpDownServerPort.Value); SocketConfig config = new SocketConfig(); config.Port = (int)this.numericUpDownServerPort.Value; config.ReceiveEndSign = "</XMLRequestMessage>"; config.SendEndSign = "</XMLResponseMessage>"; _server = SocketEntity.Create(config); if (_server == null) { return; } _server.OnRequest += new RequestEventHandler(_server_OnRequest); if (_server == null) { MessageBox.Show(SocketLogMgt.LastErrorInfor); } else if (_server.Start()) { this.numericUpDownServerPort.Enabled = false; } else { MessageBox.Show(SocketLogMgt.LastErrorInfor); } }
void OnMessageHandler(object sender, MessageEventArgs e) { string message = "Session WebSocket server said: " + e.Data; Debug.Log(message); string jsonString = System.Text.Encoding.UTF8.GetString(e.RawData); SocketEntity entity = JsonUtility.FromJson <SocketEntity>(jsonString); if ("SESSION".Equals(entity.data.type)) { if ("STARTED".Equals(entity.data.data.status) && OnSessionStarted != null) { string newSessionId = entity.data.data.sessionId; UnityMainThreadDispatcher.Instance().Enqueue(() => OnSessionStarted(newSessionId)); } } else if ("GAME".Equals(entity.data.type)) { if ("GAME_END".Equals(entity.data.data.status) && OnGameEnded != null) { UnityMainThreadDispatcher.Instance().Enqueue(() => OnGameEnded()); } } }
public void dispatchEvent(SocketEntity angent, SocketEvent e) { handle.WaitOne(); eventList.Enqueue(e); clientList.Enqueue(angent); handle.Set(); }
public static XIMServer CreateXIMServer(ServiceMain service) { XIMServer s = new XIMServer(); s._service = service; IEntity e = null; if (Program.ConfigMgt.Config.InboundFromFile) { e = new DirectoryMonitor(Program.ConfigMgt.Config.DirectoryConfig, Program.Log); } else { e = SocketEntity.Create(Program.ConfigMgt.Config.SocketConfig); } if (e == null) { return(null); } else { e.OnRequest += new RequestEventHandler(s._entity_OnRequest); s._entity = e; return(s); } }
public Permissions GetPermissions(SocketEntity <ulong> entity) { if (permissions.ContainsKey(entity.Id)) { return(permissions[entity.Id]); } return(Permissions.None); }
/// <summary> /// 替换session /// </summary> /// <param name="aobjSocketEntity">socket实体类</param> /// <param name="aobjSession"></param> private void updateSessionKey(SocketEntity aobjSocketEntity, WebSocketSession aobjSession) { gobjUserSession.Remove(aobjSession.SessionID); gobjUserSession.Remove(aobjSocketEntity.FromUser); gobjUserSession.Add(aobjSocketEntity.FromUser, aobjSession); // gobjUserTkoen.Add(aobjSession.SessionID,aobjSocketEntity.FromUser); }
void OnReceive(IAsyncResult ar) { SocketAngent client = ar.AsyncState as SocketAngent; SocketEntity socketEnt = client.socket; Socket socket = socketEnt.socket; try { int BytesRead = socket.EndReceive(ar); //if (BytesRead == 0) // return; int count = 0; if (BytesRead <= 0) { socket.BeginDisconnect(true, new AsyncCallback(this.OnDisconnect), client); return; } socketEnt.buffer.writePosition = socketEnt.buffer.writePosition + BytesRead; while (true) { if (socketEnt.buffer.Read(socketEnt.countBytes, 0, sizeof(int))) { count = System.BitConverter.ToInt32(socketEnt.countBytes, 0); count = BinaryStream.ntohl(count); if (socketEnt.buffer.validDataLength >= count) { if (socketEnt.buffer.Pop(socketEnt.recvPacket, 0, count)) { MemoryStream read_stream = new MemoryStream(socketEnt.recvPacket, sizeof(int), count - sizeof(int)); this.OnReceive(read_stream.ToArray(), socketEnt); } else { break; } } else { break; } } else { break; } } if (socketEnt.buffer.writeLength <= 0) { return; } socket.BeginReceive(socketEnt.buffer.buffer, socketEnt.buffer.writePosition, socketEnt.buffer.writeLength, 0, new AsyncCallback(this.OnReceive), client); } catch (SocketException) { this.OnDisconnect(ar); } }
public void reConnect(SocketClient client) { SocketEntity socketEnt = new SocketEntity(); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = socket.BeginConnect(socketEnt.ipPoint, this.OnConnect, client); client.socket = socketEnt; socketEnt.socket = socket; }
public void SendPacket(Packet packet, SocketEntity socket) { byte[] send_data = new byte[Shared.MAX_PACKET_LENGTH]; BinaryStream bit = new BinaryStream(send_data); packet.serialize(bit); Shared.XOR(bit.buffer, bit.wpos, ConstDef.sKey); socket.SendBuffer(bit.buffer, bit.wpos); }
void HttpService_HTTPMessageEvent(HTTPMsgEventArgs e) { if (!string.IsNullOrEmpty(e.Msg)) { SocketEntity mEntity = new SocketEntity(); mEntity.MsgType = ConstValue.MSMQTYPE.Msg_HTTP; mEntity.Msg = e.Msg; GlobalValue.Instance.SocketMag.OnSendMsg(new SocketEventArgs(mEntity)); } }
public async Task RemoveSocket(string id) { SocketEntity socket = _sockets.FirstOrDefault(p => p.SocketId == id); _sockets.TryTake(out SocketEntity item); await socket.Socket.CloseAsync(closeStatus : WebSocketCloseStatus.NormalClosure, statusDescription : "Closed by the ConnectionManager", cancellationToken : CancellationToken.None); }
public void AddSocket(WebSocket socket) { SocketEntity socketEntity = new SocketEntity() { SocketId = CreateConnectionId(), Socket = socket }; _sockets.TryAdd(socketEntity); }
public void SetPermissions(SocketEntity <ulong> entity, Permissions permissions) { if (!(entity is SocketUser) && !(entity is SocketRole)) { throw new ArgumentException("entity"); } this.permissions[entity.Id] = permissions; IsDirty = true; PermissionsChanged?.Invoke(this, entity.Id); }
public void update() { if (eventList.Count > 0) { handle.WaitOne(); SocketEvent e = eventList.Dequeue(); SocketEntity a = clientList.Dequeue(); SocketAngent angent = a.angent; handle.Set(); angent.dispatchEvent(e); } }
/// <summary> /// 处理进入房间 /// </summary> /// <param name="aobjSocketEntity">socket实体类</param> private void InRoom(SocketEntity aobjSocketEntity) { if (gobjGameRoom.ContainsKey(aobjSocketEntity.RoomID)) { gobjGameRoom[aobjSocketEntity.RoomID].Add(aobjSocketEntity.FromUser); } else { List <string> objRoom = new List <string>(); objRoom.Add(aobjSocketEntity.FromUser); gobjGameRoom.Add(aobjSocketEntity.RoomID, objRoom); } }
/// <summary> /// 处理用户退出房间 /// </summary> /// <param name="aobjSocketEntity">socket实体类</param> private void QuitRoom(SocketEntity aobjSocketEntity) { string strKey = gobjGameRoom.Where(t => t.Value.Contains(aobjSocketEntity.FromUser)).FirstOrDefault().Key; if (strKey == null) { return; } List <string> objUserList = gobjGameRoom[strKey]; objUserList.Remove(aobjSocketEntity.FromUser); gobjGameRoom[strKey] = objUserList; }
public void AddSingletonsToService(IServiceCollection collection) { Global.Client = new DiscordSocketClient(SocketEntity.GetDefault()); Global.WebClient = OriWebClient.Default; LockedDblWrapper dblWrapper = new LockedDblWrapper(Global.Client, Config["tokens:dbl"]); collection .AddSingleton <DataContainer>() // Where all data is stored. //.AddSingleton(new DiscordSocketClient(SocketEntityW.GetDefault())) // Orikivo's required boot. .AddSingleton(new CommandService(CommandEntity.GetDefault())) // Orikivo's command information. .AddSingleton <NetworkManager>() // Controls Discord connection. //.AddSingleton<EventLogger>() // Controls events that occur on Orikivo. .AddSingleton(Config); // All of the passwords for public services. }
/// <summary> /// /// </summary> /// <param name="astrRoomID"></param> /// <param name="objBet"></param> public void SendBetData(string astrRoomID, BetEntity objBet) { if (!gobjGameRoom.ContainsKey(astrRoomID)) { return; } SocketEntity objSocketMessage = new SocketEntity() { Tag = "n", ToUser = gobjGameRoom[astrRoomID], Message = JsonConvert.SerializeObject(objBet) }; handlerSendMessage(objSocketMessage); }
private void MenuItem_Offline_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(currentTerid) && Regex.IsMatch(currentTerid, @"^\d{1,3}$")) { if (DialogResult.No == XtraMessageBox.Show("是否使终端[" + currentTerid + "下线?", GlobalValue.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk)) { return; } SocketEntity msmqEntity = new SocketEntity(); msmqEntity.MsgType = ConstValue.MSMQTYPE.Cmd_Online; msmqEntity.DevId = Convert.ToInt16(currentTerid); msmqEntity.DevType = ConstValue.DEV_TYPE.UNIVERSAL_CTRL; msmqEntity.AllowOnline = false; GlobalValue.SocketMgr.SendMessage(msmqEntity); } }
void OnReceive(byte[] data, SocketEntity socketEnt) { //MemoryStream mem = new MemoryStream(data); //byte[] outBytes = null; //int outCount = 0; //angent.unCompression(data, data.Length, ref outBytes, ref outCount); //MemoryStream read_mem = new MemoryStream(outBytes, 0, outCount); SocketEvent e = new SocketEvent(); e.name = SocketEvent.RECV; e.data = data; dispatchEvent(socketEnt, e); }
void OnDisconnect(IAsyncResult ar) { SocketClient client = ar.AsyncState as SocketClient; SocketEntity socketEnt = client.socket; Socket socket = socketEnt.socket; try { socket.EndDisconnect(ar); SocketEvent e = new SocketEvent(); e.name = SocketEvent.EXIT; dispatchEvent(socketEnt, e); } catch { } }
/// <summary> /// 处理要访问方法 /// </summary> /// <param name="aSocketMessage">信息实体对象</param> /// <param name="aUserSession">用户 websocket session 可以为空</param> private void handlerControllerAction(SocketEntity aobjSocketEnriry, WebSocketSession aobjSocketSession) { JavaScriptSerializer js = new JavaScriptSerializer(); //得到要执行的方法名称和类名 string message = aobjSocketEnriry.ActionMethod; string[] am = message.Split('.'); //得到需要传入的参数 Dictionary <string, object> param = js.Deserialize <Dictionary <string, object> >(aobjSocketEnriry.Message); object backObj = null; //得到要执行的方法对象和类实例对象 ResultBase responseVo = new ResultBase(); // try // { MethodInfo method = GetActionMethod(out backObj, className: am[0], method: am[1]); //得到方法执行数据 object result = takeData(method, param, backObj); responseVo.Result = result; // } //catch (Exception ex) // { // responseVo.ErrorCode = "500"; // responseVo.ErrorMsg = ex.Message; //} //处理ResponseVo对象并发送数据 aobjSocketEnriry.Message = JsonHelper.ReplaceDateTime(js.Serialize(responseVo)); if (aobjSocketEnriry.FromUser != "") { List <string> vs = new List <string>(); vs.Add(aobjSocketEnriry.FromUser); aobjSocketEnriry.ToUser = vs; aobjSocketSession = null; } handlerSendMessage(aobjSocketEnriry, aobjSocketSession); }
void OnMessageHandler(object sender, MessageEventArgs e) { string message = "Court WebSocket server said: " + e.Data; Debug.Log(message); string jsonString = System.Text.Encoding.UTF8.GetString(e.RawData); SocketEntity entity = JsonUtility.FromJson <SocketEntity>(jsonString); if (entity.data.bid > 0) { if (OnBallPositionChanged != null) { string bid = entity.data.bid + ""; int x = entity.data.y; int y = entity.data.x; int z = entity.data.z; UnityMainThreadDispatcher.Instance().Enqueue( () => OnBallPositionChanged(bid, x, y, z) ); } } else if (entity.data.pid > 0) { if (OnPlayerPositionChanged != null) { string pid = entity.data.pid + ""; int x = entity.data.y; int y = entity.data.x; int z = entity.data.z; UnityMainThreadDispatcher.Instance().Enqueue( () => OnPlayerPositionChanged(pid, x, y, z) ); } if (entity.data.shot != null && entity.data.shot.hid != null && OnShotMade != null) { Debug.LogWarning("============== " + entity.data.shot.hid + "........" + entity.data.shot.st); UnityMainThreadDispatcher.Instance().Enqueue( () => OnShotMade(entity.data.shot.hid, entity.data.shot.st) ); } } }
/// <summary> /// 处理要访问方法 /// </summary> /// <param name="aSocketMessage">信息实体对象</param> /// <param name="aUserSession">用户 websocket session 可以为空</param> private void handlerControllerAction(SocketEntity aobjSocketEnriry, WebSocketSession aobjSocketSession) { JavaScriptSerializer js = new JavaScriptSerializer(); //得到要执行的方法名称和类名 string message = aobjSocketEnriry.ActionMethod; System.Diagnostics.Debug.WriteLine("方法名称与类名:" + message); string[] am = message.Split('.'); //得到需要传入的参数 Dictionary <string, object> param = js.Deserialize <Dictionary <string, object> >(aobjSocketEnriry.Message); object backObj = null; //得到要执行的方法对象和类实例对象 ResultBase responseVo = new ResultBase(); MethodInfo method = GetActionMethod(out backObj, className: am[0], method: am[1]); System.Diagnostics.Debug.WriteLine(method + "" + param); //得到方法执行数据 object result = takeData(method, param, backObj); System.Diagnostics.Debug.WriteLine("通过方法" + result); responseVo.Result = result; //处理ResponseVo对象并发送数据 aobjSocketEnriry.Message = JsonHelper.ReplaceDateTime(js.Serialize(responseVo)); if (aobjSocketEnriry.FromUser != "") { List <string> vs = new List <string>(); vs.Add(aobjSocketEnriry.FromUser); aobjSocketEnriry.ToUser = vs; aobjSocketSession = null; } handlerSendMessage(aobjSocketEnriry, aobjSocketSession); }