public static fireIn ( string eventname ) : void | ||
eventname | string | |
Résultat | void |
public void startRecv() { // 必须有空间可写,否则我们阻塞在线程中直到有空间为止 int first = 0; int space = _free(); while (space == 0) { if (first > 0) { if (first > 1000) { throw new Exception("PacketReceiver::startRecv(): no space!"); } Dbg.WARNING_MSG("PacketReceiver::startRecv(): waiting for space, Please adjust 'RECV_BUFFER_MAX'! retries=" + first); System.Threading.Thread.Sleep(5); } first += 1; space = _free(); } try { _networkInterface.sock().BeginReceive(_buffer, _wpos, space, 0, _asyncCallback, this); } catch (Exception e) { Dbg.ERROR_MSG("PacketReceiver::startRecv(): call ReceiveAsync() is err: " + e.ToString()); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); } }
void _startSend() { int sendSize = Interlocked.Add(ref _wpos, 0) - _spos; int t_spos = _spos % _buffer.Length; if (t_spos == 0) { t_spos = sendSize; } if (sendSize > _buffer.Length - t_spos) { sendSize = _buffer.Length - t_spos; } try { _networkInterface.sock().BeginSend(_buffer, _spos % _buffer.Length, sendSize, 0, new AsyncCallback(_onSent), this); } catch (Exception e) { Dbg.ERROR_MSG("PacketSender::startSend(): is err: " + e.ToString()); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); } }
private void _asyncReceive() { if (_networkInterface == null || !_networkInterface.valid()) { Dbg.WARNING_MSG("PacketReceiver::_asyncReceive(): network interface invalid!"); return; } var socket = _networkInterface.sock(); while (true) { // 必须有空间可写,否则我们阻塞在线程中直到有空间为止 int first = 0; int space = _free(); while (space == 0) { if (first > 0) { if (first > 1000) { Dbg.ERROR_MSG("PacketReceiver::_asyncReceive(): no space!"); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); return; } Dbg.WARNING_MSG("PacketReceiver::_asyncReceive(): waiting for space, Please adjust 'RECV_BUFFER_MAX'! retries=" + first); System.Threading.Thread.Sleep(5); } first += 1; space = _free(); } int bytesRead = 0; try { bytesRead = socket.Receive(_buffer, _wpos, space, 0); } catch (SocketException se) { Dbg.ERROR_MSG(string.Format("PacketReceiver::_asyncReceive(): receive error, disconnect from '{0}'! error = '{1}'", socket.RemoteEndPoint, se)); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); return; } if (bytesRead > 0) { // 更新写位置 Interlocked.Add(ref _wpos, bytesRead); } else { Dbg.WARNING_MSG(string.Format("PacketReceiver::_asyncReceive(): receive 0 bytes, disconnect from '{0}'!", socket.RemoteEndPoint)); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); return; } } }
/// <summary> /// 在非主线程执行:连接服务器结果回调 /// </summary> private void _asyncConnectCB(IAsyncResult ar) { ConnectState state = (ConnectState)ar.AsyncState; Dbg.DEBUG_MSG(string.Format("NetWorkInterface::_asyncConnectCB(), connect to '{0}:{1}' finish. error = '{2}'", state.connectIP, state.connectPort, state.error)); // Call EndInvoke to retrieve the results. state.caller.EndInvoke(ar); Event.fireIn("_onConnectionState", new object[] { state }); }
protected override void _asyncSend() { if (_networkInterface == null || !_networkInterface.valid()) { Dbg.WARNING_MSG("PacketSenderTCP::_asyncSend(): network interface invalid!"); return; } var socket = _networkInterface.sock(); while (true) { Monitor.Enter(_sending); int sendSize = _wpos - _spos; int t_spos = _spos % _buffer.Length; if (t_spos == 0) { t_spos = sendSize; } if (sendSize > _buffer.Length - t_spos) { sendSize = _buffer.Length - t_spos; } int bytesSent = 0; try { bytesSent = socket.Send(_buffer, _spos % _buffer.Length, sendSize, 0); } catch (SocketException se) { Dbg.ERROR_MSG(string.Format("PacketSenderTCP::_asyncSend(): send data error, disconnect from '{0}'! error = '{1}'", socket.RemoteEndPoint, se)); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); Monitor.Exit(_sending); return; } _spos += bytesSent; // 所有数据发送完毕了 if (_spos == _wpos) { _sending = false; Monitor.Exit(_sending); return; } Monitor.Exit(_sending); } }
public override void process() { Socket socket = _networkInterface.sock(); while (socket.Available > 0) { int length = 0; try { length = socket.Receive(_buffer); } catch (Exception e) { Dbg.ERROR_MSG("PacketReceiverKCP::process: " + e.ToString()); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); return; } if (length <= 0) { Dbg.WARNING_MSG("PacketReceiverKCP::_asyncReceive(): KCP Receive <= 0!"); return; } ((NetworkInterfaceKCP)_networkInterface).nextTickKcpUpdate = 0; if (kcp_.Input(_buffer, 0, length) < 0) { Dbg.WARNING_MSG(string.Format("PacketReceiverKCP::_asyncReceive(): KCP Input get {0}!", length)); return; } while (true) { length = kcp_.Recv(_buffer, 0, _buffer.Length); if (length < 0) { break; } if (_networkInterface.fileter() != null) { _networkInterface.fileter().recv(_messageReader, _buffer, 0, (MessageLengthEx)length); } else { _messageReader.process(_buffer, 0, (MessageLengthEx)length); } } } }
public void connectTo(string ip, int port, ConnectCallback callback, object userData) { if (valid()) { throw new InvalidOperationException("Have already connected!"); } if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip)) { IPHostEntry ipHost = Dns.GetHostEntry(ip); ip = ipHost.AddressList[0].ToString(); } // Security.PrefetchSocketPolicy(ip, 843); IPAddress[] hostAddresses = Dns.GetHostAddresses(ip); IPAddress[] outIPs = hostAddresses; AddressFamily addressFamily = AddressFamily.InterNetwork; if (Socket.OSSupportsIPv6 && this.IsHaveIpV6Address(hostAddresses, ref outIPs)) { addressFamily = AddressFamily.InterNetworkV6; } _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, NetworkInterface.RECV_BUFFER_MAX * 2); ConnectState state = new ConnectState(); state.connectIP = ip; state.connectPort = port; state.connectCB = callback; state.userData = userData; state.socket = _socket; state.networkInterface = this; Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ..."); // 先注册一个事件回调,该事件在当前线程触发 Event.registerIn("_onConnectStatus", this, "_onConnectStatus"); try { _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(connectCB), state); } catch (Exception e) { state.error = e.ToString(); Event.fireIn("_onConnectStatus", new object[] { state }); } }
public bool sendto(byte[] packet, int size) { try { socket_.SendTo(packet, size, SocketFlags.None, remoteEndPint_); } catch (SocketException se) { Dbg.ERROR_MSG(string.Format("PacketSenderKCP::sendto(): send data error, disconnect from '{0}'! error = '{1}'", socket_.RemoteEndPoint, se)); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); return(false); } return(true); }
void _asyncSend() { if (_networkInterface == null || !_networkInterface.valid()) { Dbg.WARNING_MSG("PacketSender::_asyncSend(): network interface invalid!"); return; } var socket = _networkInterface.sock(); while (true) { int sendSize = Interlocked.Add(ref _wpos, 0) - _spos; int t_spos = _spos % _buffer.Length; if (t_spos == 0) { t_spos = sendSize; } if (sendSize > _buffer.Length - t_spos) { sendSize = _buffer.Length - t_spos; } int bytesSent = 0; try { bytesSent = socket.Send(_buffer, _spos % _buffer.Length, sendSize, 0); } catch (SocketException se) { Dbg.ERROR_MSG(string.Format("PacketSender::_asyncSend(): send data error, disconnect from '{0}'! error = '{1}'", socket.RemoteEndPoint, se)); Event.fireIn("_closeNetwork", new object[] { _networkInterface }); return; } int spos = Interlocked.Add(ref _spos, bytesSent); // 所有数据发送完毕了 if (spos == Interlocked.Add(ref _wpos, 0)) { Interlocked.Exchange(ref _sending, 0); return; } } }
private static void connectCB(IAsyncResult ar) { try { // Retrieve the socket from the state object. NetworkInterface networkInterface = (NetworkInterface)ar.AsyncState; // Complete the connection. networkInterface.sock().EndConnect(ar); Event.fireIn("_onConnectStatus", new object[] { "" }); } catch (Exception e) { Event.fireIn("_onConnectStatus", new object[] { e.ToString() }); } }
private static void _onRecv(IAsyncResult ar) { // Retrieve the socket from the state object. PacketReceiver state = (PacketReceiver)ar.AsyncState; try { // 由于多线程问题,networkInterface可能已被丢弃了 // 例如:在连接loginapp之后自动开始连接到baseapp之前会先关闭并丢弃networkInterface if (!state.networkInterface().valid()) { return; } Socket client = state.networkInterface().sock(); // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // 更新写位置 Interlocked.Add(ref state._wpos, bytesRead); state.startRecv(); } else { if (bytesRead == 0) { Dbg.WARNING_MSG(string.Format("PacketReceiver::_processRecved(): disconnect!")); Event.fireIn("_closeNetwork", new object[] { state.networkInterface() }); return; } else { state.startRecv(); } } } catch (Exception e) { Dbg.ERROR_MSG(string.Format("PacketReceiver::_processRecved(): is error({0})!", e.ToString())); Event.fireIn("_closeNetwork", new object[] { state.networkInterface() }); } }
public void connectTo(string ip, int port, ConnectCallback callback, object userData) { if (valid()) { throw new InvalidOperationException("Have already connected!"); } if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip)) { IPHostEntry ipHost = Dns.GetHostEntry(ip); ip = ipHost.AddressList[0].ToString(); } // Security.PrefetchSocketPolicy(ip, 843); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, KBEngineApp.app.getInitArgs().getRecvBufferSize() * 2); _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.SendBuffer, KBEngineApp.app.getInitArgs().getSendBufferSize() * 2); _socket.NoDelay = true; ConnectState state = new ConnectState(); state.connectIP = ip; state.connectPort = port; state.connectCB = callback; state.userData = userData; state.socket = _socket; state.networkInterface = this; Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ..."); // 先注册一个事件回调,该事件在当前线程触发 Event.registerIn("_onConnectStatus", this, "_onConnectStatus"); try { _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(connectCB), state); } catch (Exception e) { state.error = e.ToString(); Event.fireIn("_onConnectStatus", new object[] { state }); } }
private static void connectCB(IAsyncResult ar) { ConnectState state = null; try { // Retrieve the socket from the state object. state = (ConnectState)ar.AsyncState; // Complete the connection. state.socket.EndConnect(ar); Event.fireIn("_onConnectionState", new object[] { state }); } catch (Exception e) { state.error = e.ToString(); Event.fireIn("_onConnectionState", new object[] { state }); } }
private static void _onSent(IAsyncResult ar) { // Retrieve the socket from the state object. PacketSender state = (PacketSender)ar.AsyncState; try { // 由于多线程问题,networkInterface可能已被丢弃了 // 例如:在连接loginapp之后自动开始连接到baseapp之前会先关闭并丢弃networkInterface if (!state.networkInterface().valid()) { return; } Socket client = state.networkInterface().sock(); // Complete sending the data to the remote device. int bytesSent = client.EndSend(ar); int spos = Interlocked.Add(ref state._spos, bytesSent); // 如果数据没有发送完毕需要继续投递发送 if (spos != Interlocked.Add(ref state._wpos, 0)) { state._startSend(); } else { // 所有数据发送完毕了 Interlocked.Exchange(ref state._sending, 0); } } catch (Exception e) { Dbg.ERROR_MSG(string.Format("PacketSender::_processSent(): is error({0})!", e.ToString())); Event.fireIn("_closeNetwork", new object[] { state.networkInterface() }); Interlocked.Exchange(ref state._sending, 0); } }