private void BuildMessage(String msg) { _messageBuilder.Append(msg); if (!msg.EndsWith("}") && !msg.EndsWith("]")) { return; } try { List <ChatMessage> msgs; using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms)) { sw.AutoFlush = true; sw.Write(_messageBuilder); ms.Seek(0, SeekOrigin.Begin); var serializer = new DataContractJsonSerializer(typeof(List <ChatMessage>)); msgs = serializer.ReadObject(ms) as List <ChatMessage>; } } var handler = new ReceiveHandler(MessageReceived); _dispatcher.BeginInvoke(handler, new[] { msgs }); } catch { } _messageBuilder.Length = 0; }
protected virtual void Dispose(bool disposing) { if (m_disposed) { return; } //if (disposing) { } m_handlerDisconnected = null; m_handlerReceived = null; m_saeaReciver = null; m_saeaSender = null; m_pooledBufferManager = null; m_queueSend = null; m_listSend.Clear(); m_listSend = null; m_bClosed = null; m_bClosing = null; m_bSending = null; m_bReceiving = null; m_disposed = true; }
/// <summary> /// 从指定的队列获取消息 /// </summary> /// <param name="queueName">队列名称</param> /// <param name="receiveHandler">接收到消息之后的处理方法</param> /// <returns>是否获取到了消息</returns> public bool GetMessage(string queueName, ReceiveHandler receiveHandler) { string exchangeName = queueName + ".exchange"; string routingKey = queueName + ".routingKey"; using (var connection = _factory.CreateConnection()) { using (var channel = connection.CreateModel()) { //声明队列 DeclareQueue(channel, queueName, exchangeName, routingKey); BasicGetResult res = channel.BasicGet(queueName, false); if (res != null) { string data = Encoding.UTF8.GetString(res.Body); bool res1 = receiveHandler(data); if (res1) { channel.BasicAck(res.DeliveryTag, false); } return true; } else { return false; } } } }
public SSDPSession(Socket TheSocket, ReceiveHandler RequestCallback, bool Unicast) { this.UNICAST = false; this.MainBuffer = new byte[0x1000]; this.Buffer = new MemoryStream(); if (RequestCallback != null) { this.OnReceive = (ReceiveHandler)Delegate.Combine(this.OnReceive, RequestCallback); } this.MainSocket = new AsyncSocket(0x2000); this.MainSocket.Attach(TheSocket); this.MainSocket.SetTTL(4); this.MainSocket.OnReceive += new AsyncSocket.OnReceiveHandler(this.HandleReceive); this.MainSocket.OnDisconnect += new AsyncSocket.ConnectHandler(this.HandleDisconnect); this.MainSocket.OnSendReady += new AsyncSocket.OnSendReadyHandler(this.HandleReady); if (!Unicast) { this.UNICAST = true; if (((IPEndPoint)TheSocket.LocalEndPoint).Address.ToString() != "127.0.0.1") { this.MainSocket.AddMembership((IPEndPoint)TheSocket.LocalEndPoint, IPAddress.Parse("239.255.255.250")); } } this.MainSocket.Begin(); }
public Faden(MyDelegate Funktion, ReceiveHandler EventFunktion = null, string Name = "Thread", Boolean autoStart = true) { try { name = Name; funktion = Funktion; //Dump Evaluationsthread starten //Thread im Hintergrund laufen lassen thread = new Thread(new ThreadStart(Working)); thread.IsBackground = true; if (autoStart == true) { thread.Start(); } if (EventFunktion != null) { //Verknüpfe Methode des Hauptprogramm mit dieser Klasse um Daten zu übermitteln _meinEvent += new ReceiveHandler(EventFunktion); } else { _meinEvent = null; } } catch (Exception ex) //Thread konnte nicht eingerichtet werden { errorMessage = ex; } }
public void Close() { if (client != null) { IsActive = false; cancelToken.Cancel(); OnReceive = null; client.Close(); } }
/// <summary> /// Creates a new instance with the specified options. /// </summary> /// <param name="receiveHandler">The handler of received data.</param> public UdpClientSocket(ReceiveHandler receiveHandler) { _receiveHandler = receiveHandler; _socket = new Socket(SocketType.Dgram, ProtocolType.Udp) { ReceiveBufferSize = DoubleProtocol.UdpSocketBufferSize, SendBufferSize = DoubleProtocol.UdpSocketBufferSize, ReceiveTimeout = DoubleProtocol.SocketOperationTimeout, SendTimeout = DoubleProtocol.SocketOperationTimeout }; }
public void registerIOHandler(byte port, ReceiveHandler rcv, SendHandler snd) { if (rcv != null) { m_INHandler.Add(port, rcv); } if (snd != null) { m_OUTHandler.Add(port, snd); } }
/// <summary> /// 构造 /// </summary> /// <param name="hostName"></param> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="delegate_ReceiveHandler"></param> public Server(string hostName, string ip, int port, ReceiveHandler delegate_ReceiveHandler) { HostName = hostName; IP = ip; Port = port; Delegate_ReceiveHandler = delegate_ReceiveHandler; tcpServer = new TCP_Server <TCP_ServerSession>(); tcpServer.Bindings = new LumiSoft.Net.IPBindInfo[] { new IPBindInfo(HostName, LumiSoft.Net.BindInfoProtocol.TCP, System.Net.IPAddress.Parse(IP), Port) }; tcpServer.SessionCreated += new EventHandler <TCP_ServerSessionEventArgs <TCP_ServerSession> >(tcpServer_SessionCreated); }
private static void InvokeHandler(ReceiveHandler handler, Message msg, Connection connection) { bool async = handler.GetMethodInfo().GetCustomAttributes(typeof(AsyncOperationAttribute), false).Length > 0; if (async) { ThreadPool.QueueUserWorkItem((o) => handler.Invoke(msg, connection)); } else { handler.Invoke(msg, connection); } }
/// <summary> /// Initializes a new instance of the FeedWorker. /// </summary> /// <param name="receiveCallback">A ReceiveHandler callback.</param> /// <param name="checkInterval">An interval (milliseconds) to start receiving RSS feeds.</param> public FeedWorker(ReceiveHandler receiveCallback, int checkInterval) { this.receiveCallback = receiveCallback; FeedWorker.checkInterval = checkInterval; this.stop = false; //#if !CF // resetEvent = new AutoResetEvent(false); //#else resetEvent = new EventWaitHandle(false, EventResetMode.ManualReset); //#endif feedList = new ArrayList(); timer = new Timer(new TimerCallback(TimerCall), resetEvent, Timeout.Infinite, Timeout.Infinite); }
/// <summary> /// 发送消息到客户端 /// </summary> /// <param name="info"></param> /// <param name="toName"></param> private void SendToClient(object info, string toName) { foreach (var v in _remotingObject.GetServerEventList()) { try { ReceiveHandler receive = (ReceiveHandler)v; receive.BeginInvoke(info, toName, null, null); } catch { } } //_remotingObject.ToClient(txtSend.Text, txtName.Text); }
/// <summary> /// Add handler to message specific message type /// </summary> /// <param name="type">Message type</param> /// <param name="handler">handler to process messages with selected type</param> public void AddHandler(short type, ReceiveHandler handler) { lock (_receiveHandlers) { if (_receiveHandlers.ContainsKey(type)) { _receiveHandlers[type].Add(handler); } else { IList <ReceiveHandler> list = new List <ReceiveHandler>(); list.Add(handler); _receiveHandlers.Add(type, list); } } }
private void AddMessage(ChatMessage msg) { if (_dispatcher != null) { var handler = new ReceiveHandler(MessageReceived); _dispatcher.BeginInvoke(handler, new[] { new List <ChatMessage> { msg } }); } else { MessageReceived(new List <ChatMessage> { msg }); } }
/* ~DataListener() * { * var MineCon = IoC.Resolve<MineConfig>(); * MineCon.Save(); * } */ public void Init(ReceiveHandler Function) { _dataExchange.ReceiveEvent += Function; if (IoC.Resolve <MineConfig>().CanName.Contains("CAN")) { _dataExchange.StartExchange(IoC.Resolve <MineConfig>().CanName, IoC.Resolve <MineConfig>().CanSpeed, new AdvCANIO()); } else if (IoC.Resolve <MineConfig>().CanName.Contains("COM")) { _dataExchange.StartExchange(IoC.Resolve <MineConfig>().CanName, IoC.Resolve <MineConfig>().CanSpeed, new ComCANIO()); } //_dataExchange.StartExchange("COM7",50, new ComCANIO()); //_dataExchange.StartExchange("myNonPersisterMemoryMappedFile"); }
/// <summary> /// Handles communications between the Scala Agents and the Unity NPCs. /// </summary> public Communicator(ReceiveHandler handler, IPEndPoint remote) { //Create the endpoint. //IPAddress[] address = Dns.GetHostAddresses("localhost"); this.endpoint = remote; //Create the socket. this.client = new TcpClient(); this.client.NoDelay = true; this.delimiter = UTF8Encoding.UTF8.GetBytes(";")[0]; //Specify handler and callbacks. this.Handle = handler; this.OnConnect = this.ConnectCallback; this.OnSend = this.SendCallback; this.OnReceive = this.ReceiveCallback; }
/// <summary> /// Creates a new instance with the specified options. /// </summary> /// <param name="successfulConnectHandler">The handler of the successful connection.</param> /// <param name="failedConnectHandler">The handler of the failed connection.</param> /// <param name="receiveHandler">The handler of received data.</param> /// <param name="connectionLostHandler">The handler of the disconnect.</param> public TcpClientSocket(SuccessfulConnectHandler successfulConnectHandler, FailedConnectHandler failedConnectHandler, ReceiveHandler receiveHandler, ConnectionLostHandler connectionLostHandler) { _successfulConnectHandler = successfulConnectHandler; _failedConnectHandler = failedConnectHandler; _receiveHandler = receiveHandler; _connectionLostHandler = connectionLostHandler; _socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { ReceiveBufferSize = DoubleProtocol.TcpSocketBufferSize, SendBufferSize = DoubleProtocol.TcpSocketBufferSize, ReceiveTimeout = DoubleProtocol.SocketOperationTimeout, SendTimeout = DoubleProtocol.SocketOperationTimeout, NoDelay = true }; _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); }
private static void InvokeHandler(ReceiveHandler handler, Message msg, Connection.Connection connection) { if (Dispatcher.IsInitialized) { Dispatcher.RunOnMainThread(handler, msg, connection); return; } var async = handler.GetType().GetCustomAttributes(typeof(AsyncOperationAttribute), false).Length > 0; if (async) { ThreadPool.QueueUserWorkItem((o) => handler.Invoke(msg, connection)); } else { handler.Invoke(msg, connection); } }
/// <summary> /// Creates a new instance with the specified options and instantly starts it. /// </summary> /// <param name="newConnectionHandler">The handler of new connections.</param> /// <param name="receiveHandler">The handler of received data.</param> /// <param name="connectionLostHandler">The handler of disconnects.</param> /// <param name="connectedSockets">A collection which always contains all connected sockets.</param> /// <param name="maxPendingConnections">The maximum count of pending connections (backlog).</param> /// <param name="port">The port the server should listen on.</param> public TcpServerSocket(NewConnectionHandler newConnectionHandler, ReceiveHandler receiveHandler, ConnectionLostHandler connectionLostHandler, ICollection <Socket> connectedSockets, int maxPendingConnections, int port) { _newConnectionHandler = newConnectionHandler; _receiveHandler = receiveHandler; _connectionLostHandler = connectionLostHandler; _connectedSockets = connectedSockets; _socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { ReceiveBufferSize = DoubleProtocol.TcpSocketBufferSize, SendBufferSize = DoubleProtocol.TcpSocketBufferSize, ReceiveTimeout = DoubleProtocol.SocketOperationTimeout, SendTimeout = DoubleProtocol.SocketOperationTimeout, NoDelay = true }; _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); _socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port)); _socket.Listen(maxPendingConnections); StartAccepting(); }
public void Disconnect() { lock (this) { try{ if (!cancelToken.IsCancellationRequested) { cancelToken.Cancel(); OnReceive = null; nStream.Close(); client.Close(); if (Global.SyncContext != null) { Global.SyncContext.Post((state) => { if (OnDisconnected != null) { OnDisconnected(this); } }, null); } else { if (OnDisconnected != null) { OnDisconnected(this); } } } }catch//(Exception e) { //Util.Log("Disconnect" + e.Message); } } }
/// <summary> /// Creates a new instance with the specified options and instantly starts it. /// </summary> /// <param name="receiveHandler">The handler of received data.</param> /// <param name="port">The port the server should listen on.</param> public UdpServerSocket(ReceiveHandler receiveHandler, int port) { _receiveHandler = receiveHandler; _port = port; _socket = new Socket(SocketType.Dgram, ProtocolType.Udp) { ReceiveBufferSize = DoubleProtocol.UdpSocketBufferSize, SendBufferSize = DoubleProtocol.UdpSocketBufferSize, ReceiveTimeout = DoubleProtocol.SocketOperationTimeout, SendTimeout = DoubleProtocol.SocketOperationTimeout }; _socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port)); SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs(); eventArgs.Completed += OnReceived; eventArgs.SetBuffer(new byte[DoubleProtocol.UdpBufferArraySize], 0, DoubleProtocol.UdpBufferArraySize); eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, _port); if (!_socket.ReceiveFromAsync(eventArgs)) { OnReceived(null, eventArgs); } }
protected virtual void ConnectWork() { try { PrepareSocket(); if (_Socket != null) { byte[] receivebuffer = new byte[CONST.MTU]; int receivecnt = 0; Action BeginReceive = () => { _Socket.BeginReceive(receivebuffer, 0, 1, SocketFlags.None, ar => { try { receivecnt = _Socket.EndReceive(ar); if (receivecnt > 0) { var bytesRemaining = _Socket.Available; if (bytesRemaining > 0) { if (bytesRemaining > CONST.MTU - 1) { bytesRemaining = CONST.MTU - 1; } receivecnt += _Socket.Receive(receivebuffer, 1, bytesRemaining, SocketFlags.None); } } else { if (_ConnectWorkRunning) { _ConnectWorkCanceled = true; } } } catch (Exception e) { if (IsConnectionAlive) { _ConnectWorkCanceled = true; PlatDependant.LogError(e); } } _HaveDataToSend.Set(); }, null); }; BeginReceive(); while (!_ConnectWorkCanceled) { if (receivecnt > 0) { if (_OnReceive != null) { _OnReceive(receivebuffer, receivecnt, _Socket.RemoteEndPoint); } receivecnt = 0; BeginReceive(); } BufferInfo binfo; while (_PendingSendMessages.TryDequeue(out binfo)) { var message = binfo.Buffer; int cnt = binfo.Count; if (_OnSend != null && _OnSend(message, cnt)) { if (_OnSendComplete != null) { _OnSendComplete(message, true); } } else { SendRaw(message, cnt, success => { if (_OnSendComplete != null) { _OnSendComplete(message, success); } }); } } _HaveDataToSend.WaitOne(); } _Socket.Shutdown(SocketShutdown.Both); } } catch (ThreadAbortException) { Thread.ResetAbort(); } catch (Exception e) { PlatDependant.LogError(e); } finally { _ConnectWorkRunning = false; _ConnectWorkCanceled = false; if (_PreDispose != null) { _PreDispose(this); } if (_Socket != null) { _Socket.Close(); _Socket = null; } // set handlers to null. _OnReceive = null; _OnSend = null; _OnSendComplete = null; _PreDispose = null; } }
public new void Dispose() { OnReceive -= new ReceiveHandler(ValueServer_OnBaseReceive); base.Dispose(); }
public void SetReceiveFunction(ReceiveHandler Function) { _dataExchange.ReceiveEvent += Function; }
protected virtual void ConnectWork() { try { if (_Url != null) { bool isMulticastOrBroadcast = false; int port = 0; Uri uri = new Uri(_Url); port = uri.Port; var addresses = Dns.GetHostAddresses(uri.DnsSafeHost); if (addresses != null && addresses.Length > 0) { var address = addresses[0]; if (address.AddressFamily == AddressFamily.InterNetwork) { if (address.Equals(IPAddress.Broadcast)) { isMulticastOrBroadcast = true; } else { var firstb = address.GetAddressBytes()[0]; if (firstb >= 224 && firstb < 240) { isMulticastOrBroadcast = true; } } } else if (address.AddressFamily == AddressFamily.InterNetworkV6) { if (address.IsIPv6Multicast) { isMulticastOrBroadcast = true; } } _Socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); if (isMulticastOrBroadcast) { _Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); if (address.AddressFamily == AddressFamily.InterNetworkV6) { #if NET_STANDARD_2_0 || NET_4_6 // Notice: it is a pitty that unity does not support ipv6 multicast. (Unity 5.6) _Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(address)); _Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, 5); #endif _Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 0)); } else { if (!address.Equals(IPAddress.Broadcast)) { _Socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(address, IPAddress.Any)); _Socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 5); } _Socket.Bind(new IPEndPoint(IPAddress.Any, 0)); } _BroadcastEP = new IPEndPoint(address, port); } else { _Socket.Connect(address, port); } } } if (_Socket != null) { if (_PreStart != null) { _PreStart(this); } byte[] receivebuffer = new byte[CONST.MTU]; int receivecnt = 0; EndPoint broadcastRespEP; if (_BroadcastEP != null && _BroadcastEP.AddressFamily == AddressFamily.InterNetworkV6) { broadcastRespEP = new IPEndPoint(IPAddress.IPv6Any, 0); } else { broadcastRespEP = new IPEndPoint(IPAddress.Any, 0); } Action BeginReceive = () => { if (_BroadcastEP != null) { _Socket.BeginReceiveFrom(receivebuffer, 0, CONST.MTU, SocketFlags.None, ref broadcastRespEP, ar => { try { receivecnt = _Socket.EndReceiveFrom(ar, ref broadcastRespEP); } catch (Exception e) { if (IsConnectionAlive) { _ConnectWorkCanceled = true; PlatDependant.LogError(e); } } _HaveDataToSend.Set(); }, null); } else { _Socket.BeginReceive(receivebuffer, 0, CONST.MTU, SocketFlags.None, ar => { try { receivecnt = _Socket.EndReceive(ar); } catch (Exception e) { if (IsConnectionAlive) { _ConnectWorkCanceled = true; PlatDependant.LogError(e); } } _HaveDataToSend.Set(); }, null); } }; if (_OnReceive != null) { BeginReceive(); } while (!_ConnectWorkCanceled) { if (_OnReceive != null) { if (receivecnt > 0) { if (_BroadcastEP != null && _WaitForBroadcastResp) { _OnReceive(receivebuffer, receivecnt, broadcastRespEP); receivecnt = 0; BeginReceive(); } else { if (_BroadcastEP != null) { _Socket.Connect(broadcastRespEP); _BroadcastEP = null; } _OnReceive(receivebuffer, receivecnt, _Socket.RemoteEndPoint); receivecnt = 0; BeginReceive(); } } } if (!HoldSending) { BufferInfo binfo; while (_PendingSendMessages.TryDequeue(out binfo)) { var message = binfo.Buffer; int cnt = binfo.Count; if (_OnSend != null && _OnSend(message, cnt)) { if (_OnSendComplete != null) { _OnSendComplete(message, true); } } else { SendRaw(message, cnt, success => { if (_OnSendComplete != null) { _OnSendComplete(message, success); } }); } } } if (_OnUpdate != null) { _OnUpdate(this); } var waitinterval = _UpdateInterval; var easeratio = _EaseUpdateRatio; if (waitinterval > 0 && easeratio > 0) { var easeinterval = waitinterval * easeratio; if (_LastSendTick + easeinterval <= System.Environment.TickCount) { waitinterval = easeinterval; } } _HaveDataToSend.WaitOne(waitinterval); } } } catch (ThreadAbortException) { Thread.ResetAbort(); } catch (Exception e) { PlatDependant.LogError(e); } finally { _ConnectWorkRunning = false; _ConnectWorkCanceled = false; if (_PreDispose != null) { _PreDispose(this); } if (_Socket != null) { _Socket.Close(); _Socket = null; } // set handlers to null. _OnReceive = null; _OnSend = null; _OnSendComplete = null; _OnUpdate = null; _PreDispose = null; } }
public SSDPSession(Socket TheSocket, ReceiveHandler RequestCallback) : this(TheSocket, RequestCallback, false) { }
private void OnReceiveHandler(byte[] obj) { ReceiveHandler?.Invoke(obj); }
/// <summary> /// 设置处理接收 /// </summary> /// <param name="receive"></param> public void SetHandleReceive(ReceiveHandler receive) { mHandleReceive = receive; }
/// <summary> /// Attach to an existing Socket /// </summary> /// <param name="Local">A Specific Local IPEndPoint</param> /// <param name="TheSocket">The Socket</param> /// <param name="HeaderCallback">Header Callback</param> /// <param name="RequestCallback">Request/Response callback</param> public HTTPSession(IPEndPoint Local, Socket TheSocket, ReceiveHeaderHandler HeaderCallback, ReceiveHandler RequestCallback):this(Local,TheSocket) { if (HeaderCallback!=null) { OnHeader += HeaderCallback; } if (RequestCallback!=null) { OnReceive += RequestCallback; } MainSocket.Begin(); }
/// <summary> /// Attach to an existing Socket /// </summary> /// <param name="TheSocket">The socket to use</param> /// <param name="HeaderCallback">Header Callback</param> /// <param name="RequestCallback">Request/Responses callback</param> public HTTPSession(Socket TheSocket, ReceiveHeaderHandler HeaderCallback, ReceiveHandler RequestCallback):this((IPEndPoint)TheSocket.LocalEndPoint,TheSocket,HeaderCallback, RequestCallback) { }
public JSProxyObj(ReceiveHandler handler) { OnReceive = handler; }
protected virtual void OnReceiveHandler(byte[] obj) { ReceiveHandler?.Invoke(obj); }
public static void SetOnReceiveHandler(ReceiveHandler handler) { OnReceive = handler; }