/// <summary> /// TCP Server/Client에 접속 /// </summary> /// <param name="tcpInfo">TCP 통신 정보 객체</param> /// <returns>함수 실행 결과 (FuncResult 객체)</returns> public CommonStruct.FuncResult Connect(TcpInfo tcpInfo = null) { CommonStruct.FuncResult result = new CommonStruct.FuncResult(); stopWatch.Start(); try { if (tcpInfo == null && this.tcpInfo == null) { result.isSuccess = false; } else { if (tcpHandle == null) { tcpHandle = new TcpClient(); } if (tcpInfo != null) { tcpHandle.Connect(tcpInfo.ipAddress, tcpInfo.portNo); this.tcpInfo = tcpInfo; } else { tcpHandle.Connect(this.tcpInfo.ipAddress, this.tcpInfo.portNo); } if (tcpHandle.Connected) { result.isSuccess = true; } else { result.isSuccess = false; } } } catch (Exception ex) { result.isSuccess = false; result.funcException = ex; } stopWatch.Stop(); result.totalMilliseconds = stopWatch.ElapsedMilliseconds; stopWatch.Reset(); return(result); }
private static void ProcessDataInfo(string BlocoTotal, ref TCPProcess.TcpInfo[] TCPConnects) { string[] Linhas = BlocoTotal.Split(new char[] { '\n' }); int ConnCount = 0; char[] Splitter = new char[] { ' ' }; checked { int num = Linhas.Count <string>() - 1; for (int Total = 0; Total <= num; Total++) { string sLine = Linhas[Total].Trim(); bool flag = !string.IsNullOrEmpty(sLine); if (flag) { bool flag2 = Total > 3; if (flag2) { bool flag3 = sLine.StartsWith("TCP"); if (flag3) { TCPConnects = (TcpInfo[])Utils.CopyArray(TCPConnects, new TcpInfo[ConnCount + 1]); string[] _4Partes = sLine.Split(Splitter, StringSplitOptions.RemoveEmptyEntries); ref TcpInfo ptr = ref TCPConnects[ConnCount]; ptr.LocalIP = _4Partes[1].Split(new char[] { ':' })[0]; ptr.LocalPort = _4Partes[1].Split(new char[] { ':' })[1]; ptr.RemoteIP = _4Partes[2].Split(new char[] { ':' })[0]; ptr.RemotePort = _4Partes[2].Split(new char[] { ':' })[1]; ptr.State = _4Partes[3]; ptr.PID = Convert.ToInt32(_4Partes[4]); ConnCount++; } } } } }
/// <summary> /// Parameter를 사용하여 Propery 초기화 /// </summary> /// <param name="tcpInfo">TCP 통신 정보 객체 (생략할 경우 이후 초기화 필요)</param> public TcpHandler(TcpInfo tcpInfo = null) { this.tcpHandle = new TcpClient(); if (tcpInfo != null) { this.tcpInfo = tcpInfo; } else { this.tcpInfo = new TcpInfo(); } }
/// <summary> /// Parameter를 사용하여 Propery 초기화 /// </summary> /// <param name="tcpInfo">Socket 통신 정보 객체</param> public ModbusTcpHandler(TcpInfo tcpInfo) { byte[] TRANSACTION_ID = new byte[] { 0x00, 0x00 }; byte[] PROTOCOL_ID = new byte[] { 0x00, 0x00 }; byte[] LENGTH = new byte[] { 0x00, 0x06 }; byte[] UNIT_ID = new byte[] { 0x01 }; tcpHandler = new TcpHandler(tcpInfo); hDataUnit = new List <byte>(); hDataUnit.AddRange(TRANSACTION_ID); hDataUnit.AddRange(PROTOCOL_ID); hDataUnit.AddRange(LENGTH); hDataUnit.AddRange(UNIT_ID); }
private void SendString(string str) { try { //将字符串写入网络,此方法会自动附加字符串长度前缀 bw.Write(str); bw.Flush(); //提示发送成功 TcpInfo.AppendText("发送:" + str); } catch { //提示发送失败 TcpInfo.AppendText("发送失败!"); } }
public static void Connect(IPEndPoint ip) { if (!CheckNet()) { return; } if (Status != NetStatus.Null) { Debug.LogError("请先退出Net状态:" + Status); return; } if (info != null) { Debug.LogWarning("请勿重复连接tcp服务器"); } else { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IP, Port)); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); listen = new Thread(() => { try { Debug.Log("开始连接tcp服务器……"); socket.Connect(ip); info = new TcpInfo(socket); info.CloseEvent += () => { info = null; Net.Status = NetStatus.Null; Debug.Log("断开tcp服务器"); }; info.Receive(); Net.Status = NetStatus.Client; Debug.Log("成功连接tcp服务器:" + socket.RemoteEndPoint.ToString()); } catch (Exception e) { Debug.LogError("连接tcp服务器失败,提示:" + e.Message.ToString()); } }); listen.Start(); } }
public static void ShutDown() { if (socket != null) { listen.Abort(); if (info != null) { info.Close(); info = null; } socket = null; Net.Status = NetStatus.Null; } else { Debug.LogWarning("未连接服务器"); } }
private ModbusTcpHandler sollaeHandle; // ModbusTCP 핸들 #endregion #region Constructor public InterfaceSollae(CommInfo commInfo) { try { TcpInfo tcpInfo = new TcpInfo(commInfo.machineIp, commInfo.machinePort); base.division = "IO"; base.commInfo = commInfo; base.isConnect = false; //base.sendData = new Dictionary<string, object>(); //base.receiveData = new Dictionary<string, object>(); sollaeHandle = new ModbusTcpHandler(tcpInfo); } catch (Exception ex) { LogHandler.WriteLog(base.division, string.Format("{0} :: Constructor Exception :: Message = {1}", this.ToString(), ex.Message)); } }
public void BeginMonitoringConnectionsAsync() { backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += (s, e) => { while (true) { var newConnections = IpHlpApi.GetTcpTableEx(); // for each old entry that doesnt exist in new list, remove for (int i = 0; i < TcpInfo.Count; i++) { var existingFound = newConnections.Any(x => TcpInfo[i].Equals(x)); if (!existingFound) { new Action(() => TcpInfo.RemoveAt(i)).ExecuteInSpecificThread(dispatcher); i--; } } // for each new entry that doesnt exist, add for (int i = 0; i < newConnections.Length; i++) { bool existingFound = TcpInfo.Any(x => x.Equals(newConnections[i])); if (!existingFound) { var entry = new TcpConnection(newConnections[i].LocalPort, newConnections[i].LocalAddress.ToString(), newConnections[i].RemotePort, newConnections[i].RemoteAddress.ToString(), newConnections[i].dwOwningPid, newConnections[i].dwState, AsyncPropertyPendingText, AsyncPropertyLoadingText); new Action(() => TcpInfo.Add(entry)).ExecuteInSpecificThread(dispatcher); } } Thread.Sleep((int)RefreshInterval.TotalMilliseconds); } }; backgroundWorker.RunWorkerAsync(); }
public void SendInsightMetrics( HttpWebRequest request, HttpWebResponse response, SslProtocols?sslProtocol, Int32 retries, DateTime start, DateTime startRequest, DateTime endRequest) { try { var clientInfo = new ClientInfo { Name = SDK.ClientName, Version = SDK.Version, }; var productId = GetHeaderValue(request, HEADER_X_PRODUCT_ID); var businessFlow = GetHeaderValue(request, HEADER_X_INSIGHTS_BUSINESS_FLOW); BusinessFlowInfo businessFlowInfo = null; if (!String.IsNullOrEmpty(productId) || !String.IsNullOrEmpty(businessFlow)) { businessFlowInfo = new BusinessFlowInfo { Uid = productId, Name = businessFlow, }; } DTO.EventInfo eventInfo = null; var eventName = GetHeaderValue(request, HEADER_X_INSIGHTS_EVENT_NAME); if (!String.IsNullOrEmpty(eventName)) { eventInfo = new DTO.EventInfo { Name = eventName, }; } var protocolHttp = new ProtocolHttp { RequestUrl = request.Address.ToString(), RequestMethod = request.Method, ResponseCode = (Int32)response.StatusCode, FirstByteTime = startRequest.Subtract(start).Milliseconds, LastByteTime = endRequest.Subtract(startRequest).Milliseconds, }; for (int i = 0; i < request.Headers.Count; i++) { var header = request.Headers.GetKey(i); if (header.Equals(HEADER_X_INSIGHTS_DATA_ID, StringComparison.InvariantCultureIgnoreCase) || header.Equals("User-Agent", StringComparison.InvariantCultureIgnoreCase)) { continue; } protocolHttp.AddRequestHeader(header, String.Join(";", request.Headers.GetValues(i))); } for (int i = 0; i < response.Headers.Count; i++) { var header = response.Headers.GetKey(i); protocolHttp.AddResponseHeader(header, String.Join(";", response.Headers.GetValues(i))); } var protocolInfo = new ProtocolInfo { Name = "http", ProtocolHttp = protocolHttp, RetryCount = retries, }; var tcpInfo = new TcpInfo { SourceAddress = GetHostAddress(), TargetAddress = GetRemoteAddress(request.ServicePoint.Address), }; var connectionInfo = new ConnectionInfo { ProtocolInfo = protocolInfo, TcpInfo = tcpInfo, CertificateInfo = GetCertificateInfo(request, sslProtocol), IsDataComplete = endRequest.Subtract(startRequest).Milliseconds > 0, }; if (!String.IsNullOrEmpty(request.UserAgent)) { connectionInfo.UserAgent = request.UserAgent; } var deviceInfo = new DeviceInfo { OsName = Environment.OSVersion.VersionString, }; var structuredMetricRequest = new StructuredMetricRequest { EventInfo = eventInfo, ClientInfo = clientInfo, BusinessFlowInfo = businessFlowInfo, ConnectionInfo = connectionInfo, DeviceInfo = deviceInfo, }; HttpWebResponse httpResponse = PostData(INSIGHTS_API_ENDPOINT_METRIC, structuredMetricRequest); httpResponse.Close(); } catch (Exception) { // Do nothing } }
public static void Listen(int listenNumber = 12) { if (!CheckNet()) { return; } if (Status != NetStatus.Null) { Debug.LogError("请先退出Net状态:" + Status); return; } if (socket != null) { Debug.LogWarning("请勿重复创建tcp服务器"); } try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IP, Port)); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.Listen(listenNumber); ClientMax = listenNumber; listen = new Thread(() => { while (socket != null) { Socket s = socket.Accept(); IPEndPoint ip = (IPEndPoint)s.RemoteEndPoint; if (Clients.ContainsIP(ip)) { if (!clients.ContainsKey(ip)) { TcpInfo n = new TcpInfo(s); clients.Add(ip, n); if (AddClientEvent != null) { AddClientEvent(Clients.GetClient(ip)); } n.Receive(); n.CloseEvent += () => { clients.Remove(ip); if (Clients.ContainsIP(ip)) { if (RemoveClientEvent != null) { RemoveClientEvent(Clients.GetClient(ip)); } Clients.Remove(ip); } Debug.Log(ip + "断开连接"); }; Debug.Log("新用户登入:" + ip); } else { s.Close(); Debug.Log("用户重复登入:" + ip); } } else { s.Close(); string i = ""; foreach (var c in Clients) { i += c.PlayerName + " :" + c.IP + "\n"; } Debug.Log("拒绝用户:" + ip + "\nClients:\n" + i); } } }); listen.Start(); Net.Status = NetStatus.Server; Debug.Log("tcp服务器开启,开始监听:" + socket.LocalEndPoint); } catch (Exception e) { socket = null; Debug.LogError("创建tcp服务器失败,错误:" + e.Message.ToString()); } }