public void Connect(EndPoint endPoint) { byte[] data = new byte[1024]; string input, stringData; int recv; Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); Console.WriteLine("Default timeout: {0}", sockopt); server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _timeout); sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); Console.WriteLine("New timeout: {0}", sockopt); string welcome = "Hello, are you there?"; data = Encoding.ASCII.GetBytes(welcome); server.SendTo(data, data.Length, SocketFlags.None, endPoint); data = new byte[1024]; try { Console.WriteLine("Waiting from {0}:", endPoint.ToString()); recv = server.ReceiveFrom(data, ref endPoint); Console.WriteLine("Message received from {0}:", endPoint.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.HostUnreachable) throw new Exception("CLOSED"); throw new Exception("TIME_OUT"); } Console.WriteLine("Stopping client"); server.Close(); }
public void run() { //MESSAGE System.Windows.Forms.MessageBox.Show("Waiting for client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, this.PORT); client = (EndPoint)sender; //MESSAGE System.Windows.Forms.MessageBox.Show("Client Connected at : {0} ", client.ToString()); while (isRunning) { data = new byte[1024]; recv = serverSocket.ReceiveFrom(data, ref client); if (recv == 0) { System.Windows.Forms.MessageBox.Show("Client Connection Lost at : {0} ", client.ToString()); isRunning = false; break; } //MESSAGE System.Windows.Forms.MessageBox.Show(Encoding.ASCII.GetString(data, 0, recv) + " " + client.ToString()); //PARSE THE DATA AND UPDATE THE AIRCRAFT } serverSocket.Close(); }
public void Permit(EndPoint endPoint) { if (permited != null) { if (permited.ContainsKey(endPoint.ToString()) == false) permited.Add(endPoint.ToString(), null); } }
public void OnIPC(System.Net.Sockets.Socket aSocket, System.Net.EndPoint ep, byte[] data) { try { if (data.Length >= 6) { /*string str; * System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); * str = enc.GetString(data);*/ string[] ip_s = ep.ToString().Split(':'); Systems.SRX_Serverinfo remoteGameServer = Systems.GetServerByEndPoint(ip_s[0], UInt16.Parse(ip_s[1])); if (remoteGameServer != null) { // decode data //Network.Servers.IPCdeCode(ref data, remoteGameServer.code); Systems.PacketReader pack = new Systems.PacketReader(data); short pcmd = pack.Int16(); if (data.Length >= 6) { switch (pcmd) { default: LogDebug.Show("[IPC] unknown command recevied {0:x}", pcmd); break; } } else { LogDebug.Show("[IPC] data to short"); } } else { LogDebug.Show("[IPC] can't find the GameServer {0}:{1}", ((IPEndPoint)ep).Address.ToString(), ip_s[1]); } } else { LogDebug.Show("[IPC] packet to short from {0}", ep.ToString()); } } catch (Exception ex) { LogDebug.Show("[IPC.OnIPC] {0}", ex); } }
public bool IsPermited(EndPoint endPoint) { if (permited == null) return true; return permited.ContainsKey(endPoint.ToString()); }
/// <summary> /// 创建客户端。 /// </summary> /// <param name="endPoint">终结点。</param> /// <returns>传输客户端实例。</returns> public ITransportClient CreateClient(EndPoint endPoint) { var key = endPoint.ToString(); return _clients.GetOrAdd(key, k => new Lazy<ITransportClient>(() => { var messageListener = new MessageListener(); Func<TcpSocketSaeaClient> clientFactory = () => { var client = new TcpSocketSaeaClient((IPEndPoint)endPoint, async (c, data, offset, count) => { if (_logger.IsEnabled(LogLevel.Information)) _logger.LogInformation("接收到数据包。"); var transportMessageDecoder = _transportMessageCodecFactory.GetDecoder(); var transportMessageEncoder = _transportMessageCodecFactory.GetEncoder(); var message = transportMessageDecoder.Decode(data.Skip(offset).Take(count).ToArray()); if (_logger.IsEnabled(LogLevel.Information)) _logger.LogInformation("接收到消息:" + message.Id); await messageListener.OnReceived(new SimpleClientMessageSender(transportMessageEncoder, c), message); }); client.Connect().Wait(); return client; }; return new TransportClient(new SimpleClientMessageSender(_transportMessageCodecFactory.GetEncoder(), clientFactory), messageListener, _logger, _serviceExecutor); })).Value; }
public KinectClient(EndPoint endPoint) { Name = "Client_" + i; IP = endPoint.ToString().Split(':')[0]; Connected = true; i++; }
/// <summary> /// 创建客户端。 /// </summary> /// <param name="endPoint">终结点。</param> /// <returns>传输客户端实例。</returns> public ITransportClient CreateClient(EndPoint endPoint) { var key = endPoint.ToString(); if (_logger.IsEnabled(LogLevel.Debug)) _logger.Debug($"准备为服务端地址:{key}创建客户端。"); return _clients.GetOrAdd(key , k => new Lazy<ITransportClient>(() => { var messageListener = new MessageListener(); _bootstrap.Handler(new ActionChannelInitializer<ISocketChannel>(c => { var pipeline = c.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new DefaultChannelHandler(messageListener)); })); var bootstrap = _bootstrap; var channel = bootstrap.ConnectAsync(endPoint); var messageSender = new NettyMessageClientSender(channel); var client = new TransportClient(messageSender, messageListener, _logger, _serializer); return client; } )).Value; }
private void addToFileList(List<string> files, EndPoint endPoint) { string directoryFile = @".\PeerDirectory\" + endPoint.ToString().Split(':')[0] + "_" + files.ElementAt(0) + ".txt"; // The file where we want to save the client/file informaiton files.RemoveAt(0); // removes port number from beginning of file list File.WriteAllLines(directoryFile, files); // Write all the data in the list to the file. // Save the list of files from the client to the directory. }
private static void sendAnswer(EndPoint ep) { try { string ipStr = ep.ToString().Split(':')[0]; TcpClient client = new TcpClient(ipStr, 9999); if (client.Connected) { Socket s = client.Client; s.Send(Encoding.ASCII.GetBytes(ipStr)); s.Close(); } client.Close(); } catch(Exception ex) { Console.WriteLine("error with {0}\n{1}", ep.ToString().Split(':')[0], ex.ToString()); } }
public static bool AcceptConnection(EndPoint ipAddress) { MaxConnections.AddConnection(ipAddress); string tempIP = ipAddress.ToString().Split(':')[0]; return (_connections[tempIP] <= _maxConnections); }
public void AddReeiveAlarm(System.Net.EndPoint ep, string server, string communication, string device, IO_PARAALARM alarm, bool result) { if (IOCenterManager.IsBackRun) { return; } //IP // 报警时间 //IO参数 //报警值 //报警类型 //报警等级 //采集站 //通道 //设备 //入库结果 if (!ucEnableAlarm.Checked) { return; } ListViewItem lvi = new ListViewItem(ep.ToString()); lvi.SubItems.Add(alarm.IO_ALARM_DATE); lvi.SubItems.Add(alarm.IO_LABEL + "[" + alarm.IO_NAME + "]"); lvi.SubItems.Add(alarm.IO_ALARM_VALUE); lvi.SubItems.Add(alarm.IO_ALARM_TYPE); lvi.SubItems.Add(alarm.IO_ALARM_LEVEL); lvi.SubItems.Add(server); lvi.SubItems.Add(communication); lvi.SubItems.Add(device); if (result) { lvi.SubItems.Add("入库成功"); } else { lvi.SubItems.Add("入库失败"); } if (listViewAlarm.IsHandleCreated) { listViewAlarm.BeginInvoke(new EventHandler(delegate { try { this.listViewAlarm.Items.Insert(0, lvi); if (this.listViewAlarm.Items.Count > int.Parse(this.cbAlarmSize.SelectedValue)) { this.listViewAlarm.Items.RemoveAt(this.listViewReceive.Items.Count - 1); } } catch { } })); } }
/// <summary> /// 接收UDP数据 /// </summary> /// <param name="memory"></param> /// <param name="endPoint"></param> private async ValueTask Listener_UDPDataHandler(Memory <byte> memory, System.Net.EndPoint endPoint) { if (_appSessions.TryGetValue(endPoint.ToString(), out var appSession)) { var readOnlymemory = (ReadOnlyMemory <byte>)memory; await FilterData(appSession, new ReadOnlySequence <byte>(readOnlymemory)); } }
public AsyncReader(IByteParser parser, byte[] buffer, IAcceptor acceptor, ISocketErrorHandler errorHandler, Socket socket) { _parser = parser; _buffer = buffer; _acceptor = acceptor; _errorHandler = errorHandler; _socket = socket; _endpoint = socket.RemoteEndPoint; _log = LogManager.GetLogger(_endpoint.ToString()); }
/// <summary> /// Ensures that a player isn't already in the game and adds them /// </summary> /// <param name="playerAddress">IP address of player</param> /// <param name="name">Name of player</param> /// <returns>Boolean if the add was successful</returns> public Boolean AddPlayer( EndPoint playerAddress, string name) { if (!AddressLookup.ContainsKey(playerAddress.ToString())) { AddressLookup.Add(playerAddress.ToString(), NumberPlayers); Player p = new Player(); p.Address = playerAddress; p.PlayerNumber = NumberPlayers; p.Name = name; PlayerArray.Add( p); NumberPlayers++; PlayersRemaining = NumberPlayers; return true; } else { return false; } }
// 从EndPoint提取IP地址字符串 private string EndPointToStr(System.Net.EndPoint ePoint) { string IPPoint = ePoint.ToString(); string IPStr = ""; if (IPPoint.IndexOf(":") >= 0) { IPStr = IPPoint.Substring(0, IPPoint.IndexOf(":")); } return(IPStr); }
public static void Disconnect(EndPoint ipAddress) { string tempIP = ipAddress.ToString().Split(':')[0]; if (_connections.ContainsKey(tempIP)) _connections[tempIP]--; if ((_connections.ContainsKey(tempIP)) && (_connections[tempIP] == 0)) { _connections.Remove(tempIP); //No connections... remove it from the list } }
/// <summary> /// 创建客户端。 /// </summary> /// <param name="endPoint">终结点。</param> /// <returns>传输客户端实例。</returns> public ITransportClient CreateClient(EndPoint endPoint) { var config = new TcpSocketSaeaClientConfiguration(); var key = endPoint.ToString(); return _clients.GetOrAdd(key, k => new Lazy<ITransportClient>(() => { var messageListener = new MessageListener(); var client = new TcpSocketSaeaClient((IPEndPoint)endPoint, new SimpleMessageDispatcher(messageListener, _transportMessageCodecFactory, _logger), config); client.Connect().Wait(); return new TransportClient(new SimpleClientMessageSender(_transportMessageCodecFactory.GetEncoder(), client), messageListener, _logger, _serviceExecutor); })).Value; }
void test_ipendpoint_endpoint_equal() { System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 1912); System.Net.EndPoint ep = (System.Net.IPEndPoint)ipep; print(ipep.ToString()); print(ep.ToString()); print(ipep.Equals(ep)); //System.Net.IPEndPoint ipep2 = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); //System.Net.EndPoint sender = (System.Net.EndPoint)ipep; //sender = new }
public void AddReeiveDevice(System.Net.EndPoint ep, string datetime, string server, string communication, string device, string msg, bool result) { if (IOCenterManager.IsBackRun) { return; } if (!ucReceive.Checked) { return; } ListViewItem lvi = new ListViewItem(ep.ToString()); lvi.SubItems.Add(datetime); lvi.SubItems.Add(device); lvi.SubItems.Add(communication); lvi.SubItems.Add(server); if (msg.Length > 900) { lvi.SubItems.Add(msg.Substring(0, 900) + "......"); } else { lvi.SubItems.Add(msg); } if (result) { lvi.SubItems.Add("入库成功"); } else { lvi.SubItems.Add("入库失败"); } if (listViewReceive.IsHandleCreated) { listViewReceive.BeginInvoke(new EventHandler(delegate { try { this.listViewReceive.Items.Insert(0, lvi); if (this.listViewReceive.Items.Count > int.Parse(cbReceiveSize.SelectedValue)) { this.listViewReceive.Items.RemoveAt(this.listViewReceive.Items.Count - 1); } } catch { } })); } }
public static void AddConnection(EndPoint ipAddress) { //Fetch the IP Address string tempIP = ipAddress.ToString().Split(':')[0]; if (!_connections.ContainsKey(tempIP)) { _connections.Add(tempIP, 0); } else { _connections[tempIP]++; } }
public static void AddAlert(MyMwcCheaterAlertType type, EndPoint cheaterAddress, string description) { MyMwcLog.WriteLine("Networking.MyMwcCheaterAlert - START"); MyMwcLog.IncreaseIndent(); // Write to local log too, because if sending cheater alert won't be successful, at least user can send us the log file. MyMwcLog.WriteLine("Type: " + (int)type); MyMwcLog.WriteLine("CheaterAddress: " + ((cheaterAddress == null) ? "null" : cheaterAddress.ToString())); MyMwcLog.WriteLine("Description: " + description.ToString()); MyMwcLog.DecreaseIndent(); MyMwcLog.WriteLine("Networking.MyMwcCheaterAlert - END"); }
public static string Format(EndPoint endPoint) { var dnsEndPoint = endPoint as DnsEndPoint; if (dnsEndPoint != null) { return string.Concat( dnsEndPoint.Host, ":", dnsEndPoint.Port.ToString()); } return endPoint.ToString(); }
internal static string ToString(EndPoint endpoint) { if (endpoint == null) return ""; var dns = endpoint as DnsEndPoint; if (dns == null) { return endpoint.ToString(); } else { // DnsEndPoint includes the family-type in // ToString(), but we don't want that return dns.Host + ":" + Format.ToString(dns.Port); } }
internal static string ToString(EndPoint endpoint) { var dns = endpoint as DnsEndPoint; if (dns != null) { if (dns.Port == 0) return dns.Host; return dns.Host + ":" + Format.ToString(dns.Port); } var ip = endpoint as IPEndPoint; if (ip != null) { if (ip.Port == 0) return ip.Address.ToString(); return ip.Address.ToString() + ":" + Format.ToString(ip.Port); } return endpoint == null ? "" : endpoint.ToString(); }
public Address(EndPoint endpoint) { Protocol = "tcp"; if (endpoint is DnsEndPoint) { DnsEndPoint dnsEndpoint = endpoint as DnsEndPoint; AddressString = dnsEndpoint.Host + ":" + dnsEndpoint.Port.ToString(); } else if (endpoint is IPEndPoint) { IPEndPoint ipEndpoint = endpoint as IPEndPoint; AddressString = ipEndpoint.Address.ToString() + ":" + ipEndpoint.Port.ToString(); } else { AddressString = endpoint.ToString(); } }
/// <summary> /// begin connect /// </summary> /// <param name="endPoint"></param> /// <param name="host"></param> /// <param name="callback"></param> /// <exception cref="ArgumentNullException">endPoint is null</exception> /// <exception cref="ArgumentNullException">host is null</exception> /// <exception cref="ArgumentNullException">callback is null</exception> public static void BeginConnect(EndPoint endPoint, IHost host, Action<IConnection> callback) { if (endPoint == null) throw new ArgumentNullException("endPoint"); if (host == null) throw new ArgumentNullException("host"); if (callback == null) throw new ArgumentNullException("callback"); Log.Trace.Debug(string.Concat("begin connect to ", endPoint.ToString())); var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { socket.BeginConnect(endPoint, ar => { try { socket.EndConnect(ar); socket.NoDelay = true; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); socket.ReceiveBufferSize = host.SocketBufferSize; socket.SendBufferSize = host.SocketBufferSize; } catch (Exception ex) { try { socket.Close(); socket.Dispose(); } catch { } Log.Trace.Error(ex.Message, ex); callback(null); return; } callback(new DefaultConnection(host.NextConnectionID(), socket, host)); }, null); } catch (Exception ex) { Log.Trace.Error(ex.Message, ex); callback(null); } }
public async Task<Stream> CreateStreamAsync(EndPoint endPoint, CancellationToken cancellationToken) { var stream = await _wrapped.CreateStreamAsync(endPoint, cancellationToken).ConfigureAwait(false); var sslStream = new SslStream( stream, leaveInnerStreamOpen: false, userCertificateValidationCallback: _settings.ServerCertificateValidationCallback, userCertificateSelectionCallback: _settings.ClientCertificateSelectionCallback); string targetHost; DnsEndPoint dnsEndPoint; IPEndPoint ipEndPoint; if ((dnsEndPoint = endPoint as DnsEndPoint) != null) { targetHost = dnsEndPoint.Host; } else if ((ipEndPoint = endPoint as IPEndPoint) != null) { targetHost = ipEndPoint.Address.ToString(); } else { targetHost = endPoint.ToString(); } var clientCertificates = new X509CertificateCollection(_settings.ClientCertificates.ToArray()); try { await sslStream.AuthenticateAsClientAsync(targetHost, clientCertificates, _settings.EnabledSslProtocols, _settings.CheckCertificateRevocation).ConfigureAwait(false); } catch { stream.Close(); stream.Dispose(); throw; } return sslStream; }
/// <summary> /// Tcp客户端连接断开,通知业务层 /// </summary> /// <param name="sender"></param> /// <param name="clientPoint"></param> public void OnTcpClientClosed(object sender, EndPoint clientPoint) { var token = ClientConnectManager.GetToken(clientPoint.ToString()); PacketHead head = new PacketHead(ConnectType.Tcp, PacketMsgType.Closed); head.GameId = token.GameId; head.ServerId = token.ServerId; head.Uid = token.Uid; var session = GameSessionManager.GetSession(head.GameId, head.ServerId); if (session == null) { return; } head.Address = session.GameAddress; head.EnableGzip = false; PacketMessage packet = new PacketMessage(); packet.Head = head; packet.Content = new byte[0]; if (CheckConnected(head.Address)) { OnSendToGame(head.Address, packet.ToByte()); } }
public void AddReport(System.Net.EndPoint ep, string msg) { if (IOCenterManager.IsBackRun) { return; } if (this.ucLog.Checked) { if (listViewReport.IsHandleCreated) { listViewReport.BeginInvoke(new EventHandler(delegate { try { ListViewItem lvi = new ListViewItem(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); if (ep != null) { lvi.SubItems.Add(ep.ToString() + " " + msg); } else { lvi.SubItems.Add(msg); } this.listViewReport.Items.Insert(0, lvi); if (this.listViewReport.Items.Count > int.Parse(this.cbLogSize.SelectedValue)) { this.listViewReport.Items.RemoveAt(this.listViewReport.Items.Count - 1); } } catch { } })); } } }
private void DoConnect(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress) { if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "Connect", endPointSnapshot); } // This can throw ObjectDisposedException. SocketError errorCode = SocketPal.Connect(_handle, socketAddress.Buffer, socketAddress.Size); #if TRACE_VERBOSE try { GlobalLog.Print("Socket#" + Logging.HashString(this) + "::InternalConnect() SRC:" + Logging.ObjectToString(LocalEndPoint) + " DST:" + Logging.ObjectToString(RemoteEndPoint) + " Interop.Winsock.WSAConnect returns errorCode:" + errorCode); } catch (ObjectDisposedException) { } #endif // Throw an appropriate SocketException if the native call fails. if (errorCode != SocketError.Success) { // Update the internal state of this socket according to the error before throwing. SocketException socketException = SocketExceptionFactory.CreateSocketException((int)errorCode, endPointSnapshot); UpdateStatusAfterSocketError(socketException); if (s_loggingEnabled) { Logging.Exception(Logging.Sockets, this, "Connect", socketException); } throw socketException; } if (_rightEndPoint == null) { // Save a copy of the EndPoint so we can use it for Create(). _rightEndPoint = endPointSnapshot; } GlobalLog.Print("Socket#" + Logging.HashString(this) + "::DoConnect() connection to:" + endPointSnapshot.ToString()); // Update state and performance counters. SetToConnected(); if (s_loggingEnabled) { Logging.PrintInfo(Logging.Sockets, this, SR.Format(SR.net_log_socket_connected, LocalEndPoint, RemoteEndPoint)); Logging.Exit(Logging.Sockets, this, "Connect", ""); } }
// Receives a datagram into a specific location in the data buffer and stores // the end point. public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP) { if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "ReceiveFrom", ""); } if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (!CanTryAddressFamily(remoteEP.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), "remoteEP"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } if (_rightEndPoint == null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } ValidateBlockingMode(); GlobalLog.Print("Socket#" + Logging.HashString(this) + "::ReceiveFrom() SRC:" + Logging.ObjectToString(LocalEndPoint) + " size:" + size + " remoteEP:" + remoteEP.ToString()); // We don't do a CAS demand here because the contents of remoteEP aren't used by // WSARecvFrom; all that matters is that we generate a unique-to-this-call SocketAddress // with the right address family. EndPoint endPointSnapshot = remoteEP; Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot); Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(endPointSnapshot); // This can throw ObjectDisposedException. int bytesTransferred; SocketError errorCode = SocketPal.ReceiveFrom(_handle, buffer, offset, size, socketFlags, socketAddress.Buffer, ref socketAddress.InternalSize, out bytesTransferred); // If the native call fails we'll throw a SocketException. SocketException socketException = null; if (errorCode != SocketError.Success) { socketException = new SocketException((int)errorCode); UpdateStatusAfterSocketError(socketException); if (s_loggingEnabled) { Logging.Exception(Logging.Sockets, this, "ReceiveFrom", socketException); } if (socketException.SocketErrorCode != SocketError.MessageSize) { throw socketException; } } if (!socketAddressOriginal.Equals(socketAddress)) { try { remoteEP = endPointSnapshot.Create(socketAddress); } catch { } if (_rightEndPoint == null) { // Save a copy of the EndPoint so we can use it for Create(). _rightEndPoint = endPointSnapshot; } } if (socketException != null) { throw socketException; } if (s_perfCountersEnabled) { if (bytesTransferred > 0) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, bytesTransferred); if (Transport == TransportType.Udp) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived); } } } GlobalLog.Dump(buffer, offset, bytesTransferred); if (s_loggingEnabled) { Logging.Dump(Logging.Sockets, this, "ReceiveFrom", buffer, offset, size); } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "ReceiveFrom", bytesTransferred); } return bytesTransferred; }
/// <summary> /// 处理接收到的消息 /// </summary> /// <param name="remotePoint">客户端地址端口</param> /// <param name="receivedBuffer">收到数据</param> public void _UdpServerBase_PostReceivedMsgEvent(EndPoint remotePoint, byte[] receivedBuffer) { try { SessionData sessionData = new SessionData(); //取得远端IP地址与端口号作为连接哈希表的Key sessionData.SessionID = remotePoint.ToString(); sessionData.ReceivedData = receivedBuffer; //入队列 GpsDataParser.AddInBytesQueue(sessionData); //抛出收到的数据,测试用 string received = Encoding.ASCII.GetString(receivedBuffer); OnPostUdpMsgEvent(received); } catch (Exception ex) { Logger.Error(ex, null); } }
/// <summary> /// Sends a UDP packet /// </summary> /// <param name="bytes">Packet to be sent</param> /// <param name="count">The count of bytes to send</param> /// <param name="clientEndpoint">Address of receiving client</param> /// <param name="callback"></param> public void SendUDP(byte[] bytes, int count, EndPoint clientEndpoint, AsyncCallback callback) { int start = Environment.TickCount; m_udpOutSocket.BeginSendTo(bytes, 0, count, SocketFlags.None, clientEndpoint, callback, m_udpOutSocket); int took = Environment.TickCount - start; if (took > 100 && log.IsWarnEnabled) log.WarnFormat("m_udpListen.BeginSendTo took {0}ms! (UDP to {1})", took, clientEndpoint.ToString()); }
//************* public methods ************************* /// <devdoc> /// <para>Associates a socket with an end point.</para> /// </devdoc> public void Bind(EndPoint localEP) { if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Bind", localEP); if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // // parameter validation // if (localEP==null) { throw new ArgumentNullException("localEP"); } GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Bind() localEP:" + localEP.ToString()); EndPoint endPointSnapshot = localEP; IPEndPoint ipSnapshot = localEP as IPEndPoint; // // for now security is implemented only on IPEndPoint // If EndPoint is of other type - unmanaged code permisison is demanded // if (ipSnapshot != null) { // Take a snapshot that will make it immutable and not derived. ipSnapshot = ipSnapshot.Snapshot(); // DualMode: Do the security check on the users IPv4 address, but map to IPv6 before binding. endPointSnapshot = RemapIPEndPoint(ipSnapshot); // // create the permissions the user would need for the call // SocketPermission socketPermission = new SocketPermission( NetworkAccess.Accept, Transport, ipSnapshot.Address.ToString(), ipSnapshot.Port); // // demand for them // socketPermission.Demand(); // Here the permission check has succeded. // NB: if local port is 0, then winsock will assign some>1024, // so assuming that this is safe. We will not check the // NetworkAccess.Accept permissions in Receive. } else { //< ExceptionHelper.UnmanagedPermission.Demand(); } // // ask the EndPoint to generate a SocketAddress that we // can pass down to winsock // SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPointSnapshot); DoBind(endPointSnapshot, socketAddress); if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Bind", ""); }
private void tcpClientSocket1_DataArrival(byte[] eData, System.Net.EndPoint ePoint, string eType) // 01=Red 11=Yellow 10=Green else=Black 北东南西,行右直左 { string msg = eType + " = "; for (int i = 0; i < eData.Length; i++) { msg = msg + Convert.ToString(eData[i], 16).ToUpper() + "H "; } // 获取IP地址 string RcvIpInfo = ePoint.ToString(); int IpStrLen = RcvIpInfo.IndexOf(":"); RcvIpInfo = RcvIpInfo.Substring(0, IpStrLen); if (eData.Length == 2) { if ((eData[0] == 0xFF) && (eData[1] == 0x01)) // FF 01 灯态 { string[] uStr = new string[19]; for (int i = 3; i < 19; i++) { uStr[i] = eType.Substring((i - 3) * 2, 2); } prop.State = buidState(uStr); //UpDataTable(RcvIpInfo, uStr); } else if ((eData[0] == 0xFF) && (eData[1] == 0x00)) // FF 00 一般状态 { } else if ((eData[0] == 0xFF) && (eData[1] == 0x02)) // FF 02 一般错误 { } else if ((eData[0] == 0xFF) && (eData[1] == 0x03)) // FF 03 时间 { } else if ((eData[0] == 0xFF) && (eData[1] == 0x04)) // FF 04 控制策略 40H { } else if ((eData[0] == 0xFF) && (eData[1] == 0x05)) // FF 05 控制策略 42H { } else if ((eData[0] == 0xFF) && (eData[1] == 0x06)) // FF 06 VIP控制策略 45H { } else if ((eData[0] == 0xFF) && (eData[1] == 0x07)) // FF 07 VIP控制通知 46H { } else if ((eData[0] == 0xFF) && (eData[1] == 0x08)) // FF 08 Other ExeComData { } else if ((eData[0] == 0xFF) && (eData[1] == 0x09)) // FF 09 设备编号 { } else if ((eData[0] == 0xFF) && (eData[1] == 0x0A)) // FF 0A 灯态回送周期 { } else if ((eData[0] == 0xAA) && (eData[1] == 0xDD)) // AA DD Data OK { } else if ((eData[0] == 0xAA) && (eData[1] == 0xEE)) // AA EE Data Error { } else { } } }
public void OnIPC(System.Net.Sockets.Socket aSocket, System.Net.EndPoint ep, byte[] data) { try { if (data.Length >= 6) { UInt16 pServer = (UInt16)(data[0] + (data[1] << 8)); Systems.SRX_Serverinfo remoteGameServer = Systems.GetServerByEndPoint(((IPEndPoint)ep).Address.ToString(), pServer); if (remoteGameServer != null) { // decode data Servers.IPCdeCode(ref data, remoteGameServer.code); byte pCmd = data[3]; int dLen = (int)(data[4] + (data[5] << 8)); byte crc = Servers.BCRC(data, data.Length - 1); if (data[data.Length - 1] != crc) // wrong CRC { Console.WriteLine("{1} Wrong Checksum for Server {0}", remoteGameServer.name, Product.Prefix); return; } if (data.Length >= (dLen + 6)) { if (pCmd == (byte)IPCCommand.IPC_INFO_SERVER) { if (data.Length >= 11) { remoteGameServer.maxSlots = (UInt16)(data[7] + (data[8] << 8)); remoteGameServer.usedSlots = (UInt16)(data[9] + (data[10] << 8)); remoteGameServer.lastPing = DateTime.Now; //Console.WriteLine("[IPC] Received SERVER-INFO from GameServer {1} ({0}): S={2}, MAX={3}, CUR={4}", remoteGameServer.name, remoteGameServer.id, data[6], remoteGameServer.maxSlots, remoteGameServer.usedSlots); if (remoteGameServer.status == 0 && data[6] != 0) { Console.WriteLine("{2}GameServer {0} ({1}) status changed to online", remoteGameServer.id, remoteGameServer.name, Product.Prefix); } if (remoteGameServer.status != 0 && data[6] == 0) { Console.WriteLine("{2}GameServer {0} ({1}) status changed to check", remoteGameServer.id, remoteGameServer.name, Product.Prefix); } remoteGameServer.status = data[6]; } else { } } else if (pCmd == (byte)IPCCommand.IPC_INFO_LOGIN) { if (dLen >= 4) { UInt16 IPCid = (UInt16)(data[6] + (data[7] << 8)); UInt16 IPCResult = (UInt16)(data[8] + (data[9] << 8)); byte sLen = data[10]; lock (IPCResultList) { if (IPCResultList.ContainsKey(IPCid)) { IPCResultList[IPCid].resultCode = IPCResult; if (sLen > 0) { IPCResultList[IPCid].banReason = System.Text.ASCIIEncoding.ASCII.GetString(data, 11, sLen); } } else { Console.WriteLine("[IPC] ResultList mismatch"); } } } } else { Console.WriteLine("[IPC] unknown command recevied"); } } else { Console.WriteLine("[IPC] data to short"); } } else { Console.WriteLine("[IPC] can't find the GameServer {0}:{1}", ((IPEndPoint)ep).Address.ToString(), pServer); } } else { Console.WriteLine("[IPC] packet to short from {0}", ep.ToString()); } } catch (Exception ex) { Console.WriteLine("[IPC.OnIPC] {0}", ex); } }
public void HandleMessage(ushort CommandId, ushort DataType, ref uint PayloadSize, ref uint DataCount, ref uint Parameter1, ref uint Parameter2, ref byte[] header, ref byte[] payload, ref System.Net.EndPoint iep) { switch ((CommandID)CommandId) { #region Creation of Connection and Channels case CommandID.CA_PROTO_VERSION: break; case CommandID.CA_PROTO_SEARCH: { string channelName = payload.ToCAString(); if (channelName.Contains(".")) { channelName = channelName.Split('.')[0]; } if (Server.Records.Contains(channelName)) { Server.UdpConnection.Send(ChannelFoundMessage(Parameter1), (IPEndPoint)iep); } } break; case CommandID.CA_PROTO_CLIENT_NAME: lock (Server.openConnection) { if (Server.openConnection.ContainsKey(iep.ToString())) { Server.openConnection[iep.ToString()].Username = payload.ToCAString(); } } break; case CommandID.CA_PROTO_HOST_NAME: lock (Server.openConnection) { if (Server.openConnection.ContainsKey(iep.ToString())) { Server.openConnection[iep.ToString()].Hostname = payload.ToCAString(); } } break; case CommandID.CA_PROTO_CREATE_CHAN: lock (Server.channelList) { Server.CreateEpicsChannel((int)Parameter1, iep, payload.ToCAString()); } break; case CommandID.CA_PROTO_CLEAR_CHANNEL: lock (Server.channelList) { if (Server.channelList.ContainsKey((int)Parameter1)) { Server.channelList[(int)Parameter1].Dispose(); } } break; #endregion #region Monitor case CommandID.CA_PROTO_EVENT_ADD: int mask = payload.ToUInt16(12); lock (Server.channelList) { if (Server.channelList.ContainsKey((int)Parameter1)) { Server.channelList[(int)Parameter1].AddMonitor((EpicsType)DataType, (int)DataCount, (int)Parameter2, (MonitorMask)mask); } } break; case CommandID.CA_PROTO_EVENT_CANCEL: lock (Server.channelList) { if (Server.channelList.ContainsKey((int)Parameter1)) { Server.channelList[(int)Parameter1].RemoveMonitor((int)Parameter2); } } break; case CommandID.CA_PROTO_EVENTS_OFF: break; case CommandID.CA_PROTO_EVENTS_ON: break; #endregion #region Read&Write case CommandID.CA_PROTO_READ: case CommandID.CA_PROTO_READ_NOTIFY: lock (Server.channelList) { if (Server.channelList.ContainsKey((int)Parameter1)) { Server.channelList[(int)Parameter1].ReadValue((int)Parameter2, (EpicsType)DataType, (int)DataCount); } } break; case CommandID.CA_PROTO_WRITE: lock (Server.channelList) { if (Server.channelList.ContainsKey((int)Parameter1)) { Server.channelList[(int)Parameter1].PutValue((int)Parameter2, (EpicsType)DataType, (int)DataCount, payload, false); } } break; case CommandID.CA_PROTO_WRITE_NOTIFY: lock (Server.channelList) { if (Server.channelList.ContainsKey((int)Parameter1)) { Server.channelList[(int)Parameter1].PutValue((int)Parameter2, (EpicsType)DataType, (int)DataCount, payload, true); } } break; #endregion case CommandID.CA_PROTO_ECHO: lock (Server.openConnection) { if (Server.openConnection.ContainsKey(iep.ToString())) { var con = Server.openConnection[iep.ToString()]; if ((DateTime.Now - con.EchoLastSent).TotalSeconds > 5) { con.Send(EchoMessage); con.EchoLastSent = DateTime.Now; } } } break; } }
public void Connect(n.EndPoint ep) { attemptedConnectionEndpoint = ep.ToString(); realsocket.Connect(ep); }
public new void Connect(n.EndPoint ep) { attemptedConnectionEndpoint = ep.ToString(); base.Connect(ep); }
// Associates a socket with an end point. public void Bind(EndPoint localEP) { if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "Bind", localEP); } if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (localEP == null) { throw new ArgumentNullException("localEP"); } GlobalLog.Print("Socket#" + Logging.HashString(this) + "::Bind() localEP:" + localEP.ToString()); EndPoint endPointSnapshot = localEP; IPEndPoint ipSnapshot = localEP as IPEndPoint; // For now security is implemented only on IPEndPoint. // If EndPoint is of any other type, unmanaged code permisison is demanded. if (ipSnapshot != null) { // Take a snapshot that will make it immutable and not derived. ipSnapshot = ipSnapshot.Snapshot(); endPointSnapshot = RemapIPEndPoint(ipSnapshot); // NB: if local port is 0, then winsock will assign some port > 1024, // which is assumed to be safe. } // Ask the EndPoint to generate a SocketAddress that we can pass down to native code. Internals.SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPointSnapshot); DoBind(endPointSnapshot, socketAddress); if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "Bind", ""); } }
private void server_ClientDisconnected(System.Net.EndPoint ep) { log.WriteLine("Disconnected client: " + ((ep != null) ? ep.ToString() : String.Empty)); }
internal void InternalBind(EndPoint localEP) { if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "InternalBind", localEP); } if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } GlobalLog.Print("Socket#" + Logging.HashString(this) + "::InternalBind() localEP:" + localEP.ToString()); GlobalLog.Assert(!(localEP is DnsEndPoint), "Calling InternalBind with a DnsEndPoint, about to get NotImplementedException"); // Ask the EndPoint to generate a SocketAddress that we can pass down to native code. EndPoint endPointSnapshot = localEP; Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot); DoBind(endPointSnapshot, socketAddress); if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "InternalBind", ""); } }
//IPC & Data #region IPC & Data public void OnIPC(System.Net.Sockets.Socket aSocket, System.Net.EndPoint ep, byte[] data) { try { if (data.Length >= 6) { UInt16 pServer = (UInt16)(data[0] + (data[1] << 8)); Systems.SRX_Serverinfo remoteGameServer = Systems.GetServerByEndPoint(((IPEndPoint)ep).Address.ToString(), pServer); if (remoteGameServer != null) { // decode data Servers.IPCdeCode(ref data, remoteGameServer.code); byte pCmd = data[3]; int dLen = (int)(data[4] + (data[5] << 8)); byte crc = Servers.BCRC(data, data.Length - 1); if (data[data.Length - 1] != crc) // wrong CRC { Activity("[ERROR] Code for: " + remoteGameServer.name + " does not match"); return; } if (data.Length >= (dLen + 6)) { if (pCmd == (byte)IPCCommand.IPC_INFO_SERVER) { if (data.Length >= 11) { remoteGameServer.maxSlots = (UInt16)(data[7] + (data[8] << 8)); remoteGameServer.usedSlots = (UInt16)(data[9] + (data[10] << 8)); remoteGameServer.lastPing = DateTime.Now; Activity("[NET] " + remoteGameServer.name + ": players online " + remoteGameServer.usedSlots + "/" + remoteGameServer.maxSlots + ""); if (remoteGameServer.status == 0 && data[6] != 0) { Activity("[NET] Server: " + remoteGameServer.name + " is now online"); } if (remoteGameServer.status != 0 && data[6] == 0) { Activity("[NET] Server: " + remoteGameServer.name + " is now in check state"); } remoteGameServer.status = data[6]; } else { } } else if (pCmd == (byte)IPCCommand.IPC_INFO_LOGIN) { if (dLen >= 4) { UInt16 IPCid = (UInt16)(data[6] + (data[7] << 8)); UInt16 IPCResult = (UInt16)(data[8] + (data[9] << 8)); byte sLen = data[10]; lock (IPCResultList) { if (IPCResultList.ContainsKey(IPCid)) { IPCResultList[IPCid].resultCode = IPCResult; if (sLen > 0) { IPCResultList[IPCid].banReason = System.Text.ASCIIEncoding.ASCII.GetString(data, 11, sLen); } } else { Activity("[ERROR] ResultList mismatch"); } } } } else { Activity("[ERROR] unknown command recevied"); } } else { Activity("[ERROR] data to short"); } } else { Activity("[ERROR] can't find the GameServer " + ((IPEndPoint)ep).Address.ToString() + ""); } } else { Activity("[ERROR] packet to short from " + ep.ToString() + ""); } } catch (Exception ex) { Activity("[ERROR] " + ex + ""); } }