public DebugSession(DebugClient debugClient, ApplicationType type, WebsiteParameters par, Socket socket) { Client = debugClient; this.type = type; this.WebParameters = par; communication = new TcpCommunication(socket); }
private void testConnect() { while (!isClose) { TcpCommunication tcpService = new TcpCommunication(); int timeDelay = 0; //待socket准备好 while (timeDelay < tcpService.TcpWait) { if ((tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CONNECTED) || (tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CLOSED)) { break; } Thread.Sleep(100); timeDelay = timeDelay + 1; } if (tcpService.SOCKET_STATE != TcpCommunication.TCP_SocketState.SOCKET_CONNECTED) { SystemService.isConnect = false; } else { SystemService.isConnect = true; } myLogger.Info("网关服务器连接状态:" + (SystemService.isConnect ? "正常" : "中断")); tcpService.Close(); //间隔5分钟 Thread.Sleep(5 * 60 * 1000); } }
private void btnDisconnectAuto_Click(object sender, EventArgs e) { try { // if (_loggerTask != null) // _tokenSource.Cancel(); _syncProcessor.Dispose(); _syncProcessor = null; _commandHandler.Kill(); _commandHandler.Dispose(); _commandHandler = null; _tcpCommunication.Dispose(); _tcpCommunication = null; _myFsWatcher.Dispose(); _myFsWatcher = null; SwitchAutoUiState(false); Logger.WriteDisconnectLine(); } catch (Exception ex) { SwitchAutoUiState(false); MessageBox.Show(ex.Message, @"Disconnect"); } }
static void Main(string[] args) { var serializer = new StringMessageSerializer(); var serverCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2000), serializer); using (var publisher = Scenarios.PubSub.Publisher(serverCommunication)) { var clientCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Loopback, 2000), serializer); using (Subscribe(clientCommunication, "client1")) using (Subscribe(clientCommunication, "client2")) using (Subscribe(clientCommunication, "client3")) { publisher.Broadcast("topic", new StringMessage("broadcast message 1")); publisher.Broadcast("topic", new StringMessage("broadcast message 2")); publisher.Broadcast("topic", new StringMessage("broadcast message 3")); while (_closedChannels < 3) { Thread.Sleep(0); } } } Console.ReadKey(); }
/// <summary> /// Starts the driver. This typcially sets any class variables and hooks /// any event handlers such as SerialPort ReceivedBytes, etc. /// </summary> /// <param name="configFileData">Contains the contents of any configuration files specified in the ConfigurationFileNames property.</param> public override bool StartDriver(Dictionary <string, byte[]> configFileData) { // the TCP connection on demand, send the message and close the connection again. Logger.DebugFormat("{0}: Preparing TCP connection.", this.DeviceName); // Open a new TCP session to the target _tcp = new TcpCommunication(_tcpHostName, _tcpPort); _tcp.Logger = this.Logger; _tcp.Delimiter = RX_TERMINATOR; // change the delimiter since it defaults to "\r\n". _tcp.CurrentEncoding = System.Text.ASCIIEncoding.ASCII; // this is unnecessary since it defaults to ASCII _tcp.ReceivedDelimitedString += new EventHandler <ReceivedDelimitedStringEventArgs>(_tcp_ReceivedDelimitedString); // Set up connection monitor. This is going to be very important to us, as the Infopopup service will not hold // a presistant connection, so we are going to use the ConnectionEstablished handler to send any messages we have // held in the queue to send. _tcp.ConnectionMonitorTimeout = 9000; // ensure we receive data at least once every minute so we know the connection is alive _tcp.ConnectionMonitorTestRequest = "@message\r"; // transmit a simple dummy command every 60 seconds to ensure the unit is still connected. _tcp.ConnectionEstablished += new EventHandler <EventArgs>(_tcp_ConnectionEstablished); _tcp.ConnectionLost += new EventHandler <EventArgs>(_tcp_ConnectionLost); _tcp.StartConnectionMonitor(); // Initialize and Clear the queue before we start using it. _messages = new List <string> (); // Since the target service is very dump, and we dont have a lot of possible processing, we can just go ahead // and set this drvier into ready to use state. return(true); }
public DebugSession(DebugClient debugClient, Socket socket, bool compress = false) { Client = debugClient; communication = new TcpCommunication(socket, compress, Roles.Client, Client.IsLocal, Client.Password); communication.ExtendedSendStart += (sender, args) => StatusBar.InitProgress(); communication.Progress = progress => StatusBar.Progress(progress); communication.ExtendedSendEnd += (sender, args) => StatusBar.ClearProgress(); }
/// <summary> /// Stops the driver by unhooking any event handlers and releasing any used resources. /// </summary> public override void StopDriver() { // TODO: Add any necessary cleanup logic here. if (_tcp != null) { _tcp.Dispose(); _tcp = null; } }
public ClientSession(Socket socket) { directoryName = Path.Combine(root, Path.GetRandomFileName()); remoteEndpoint = ((IPEndPoint)socket.RemoteEndPoint).Address; communication = new TcpCommunication(socket); if (!Directory.Exists("MonoRemoteDebugger")) Directory.CreateDirectory("MonoRemoteDebugger"); }
public HomeController() { if (!tcpInitialized) { tcpCommunication = new TcpCommunication(); tcpCommunication.StateChanged += StareHandler.Tcp_StateChanged; tcpCommunication.StartTcp(); tcpInitialized = true; } }
static void Main(string[] args) { Console.WriteLine("TLS example"); var serializer = new StringMessageSerializer(); var serverTlsWrapper = new ServerTlsWrapper(new X509Certificate2("server.pfx"), false, CertificateValidationCallback); ICommunication <StringMessage> serverCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2000), serializer, ChannelSettings.GetDefault(), TcpConnectionSettingsBuilder.GetDefaultSettings(), serverTlsWrapper); var server = Scenarios.RequestResponse.SetupServer(serverCommunication) .UsingNewClientHandler((sender, a) => { Console.WriteLine("channel opened"); }) .UsingRequestHandler((sender, a) => { a.Response = new StringMessage(a.Request.Message.Replace("request", "response")); }) .UsingChannelClosedHandler((sender, a) => { Console.WriteLine("channel closed"); }) .Go(); var clientTlsWrapper = new ClientTlsWrapper("SharpChannels Example Server Certificate", new X509Certificate[] { new X509Certificate2("client.pfx") }, false, CertificateValidationCallback); ICommunication <StringMessage> clientCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Loopback, 2000), serializer, ChannelSettings.GetDefault(), TcpConnectionSettingsBuilder.GetDefaultSettings(), clientTlsWrapper); var r = Scenarios.RequestResponse.Requester(clientCommunication); using (r.Channel) { r.Channel.Open(); var requester = new Requester(r.Channel); var requestMessage = new StringMessage($"request using tls"); Console.WriteLine(requestMessage); var responseMessage = requester.Request(requestMessage); Console.WriteLine(responseMessage); r.Channel.Close(); } server.Stop(); Console.ReadKey(); }
public ClientSession(Socket socket) { directoryName = Path.Combine(root, Path.GetRandomFileName()); remoteEndpoint = ((IPEndPoint)socket.RemoteEndPoint).Address; communication = new TcpCommunication(socket); if (!Directory.Exists("MonoDebugger")) { Directory.CreateDirectory("MonoDebugger"); } }
public ClientSession(Socket socket) { var basePath = new FileInfo(typeof(MonoLogger).Assembly.Location).Directory.FullName; tempContentDirectory = Path.Combine(basePath, "Temp"); remoteEndpoint = ((IPEndPoint)socket.RemoteEndPoint).Address; communication = new TcpCommunication(socket); skipLastUsedContentDirectories = GlobalConfig.Current.SkipLastUsedContentDirectories; }
static void Main(string[] args) { Console.WriteLine("Press '1' to use native (BinaryFormatter) serializer"); Console.WriteLine("Press '2' to use ProtoBuf serializer"); var serializer = RequestSerializer(); Console.WriteLine(); var serverCommunication = new TcpCommunication <Message>(new TcpEndpointData(IPAddress.Any, 2000), serializer); var server = Scenarios.RequestResponse.SetupServer(serverCommunication) .UsingRequestHandler((sender, a) => { a.Response = new Message { StringField = "Response", IntField = a.Request.IntField, DateTimeField = DateTime.Now }; }) .Go(); var clientCommunication = new TcpCommunication <Message>(new TcpEndpointData(IPAddress.Loopback, 2000), serializer); var r = Scenarios.RequestResponse.Requester(clientCommunication); using (r.Channel) { r.Channel.Open(); for (int i = 0; i < 100; i++) { var requestMessage = new Message { StringField = "Request", IntField = i, DateTimeField = DateTime.Now }; Console.WriteLine(requestMessage); var responseMessage = r.Request(requestMessage); Console.WriteLine(responseMessage); } r.Channel.Close(); } server.Stop(); Console.ReadKey(); }
private IPublisher <StringMessage> StartTcpPublisher() { var connectionSettings = new TcpConnectionSettingsBuilder() .UsingSendTimeout(TimeSpan.FromHours(1)) .Build(); var communication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2000), new StringMessageSerializer(), ChannelSettings.GetDefault(), connectionSettings, null); return(Scenarios.PubSub.Publisher(communication)); }
private IRequester GetTcpRequester() { var connectionSettings = new TcpConnectionSettingsBuilder() .UsingSendTimeout(TimeSpan.FromHours(1)) .UsingReceiveTimeout(TimeSpan.FromHours(1)) .Build(); var clientCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Loopback, 2000), new StringMessageSerializer(), ChannelSettings.GetDefault(), connectionSettings, null); return(Scenarios.RequestResponse.Requester(clientCommunication)); }
private NewChannelRequestAcceptor StartTcpServer() { var connectionSettings = new TcpConnectionSettingsBuilder() .UsingSendTimeout(TimeSpan.FromHours(1)) .UsingReceiveTimeout(TimeSpan.FromHours(1)) .Build(); var communication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2000), new StringMessageSerializer(), ChannelSettings.GetDefault(), connectionSettings, null); return(StartServer(communication)); }
private void btnConnect_Click(object sender, EventArgs e) { try { Context.InAutoMode = false; var tcpClient = new TcpClient(txtHostAuto.Text, Int32.Parse(txtPortAuto.Text)); var tcpCommunication = new TcpCommunication(tcpClient); _commandHandler = new CommandHandler(tcpCommunication); SwitchManualUiState(UiConnectedState); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static void Main(string[] args) { var serializer = new StringMessageSerializer(); var communication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2000), serializer); var server = Scenarios.RequestResponse.SetupServer(communication) .UsingNewClientHandler((sender, a) => { Console.WriteLine("channel opened"); }) .UsingRequestHandler((sender, a) => { a.Response = new StringMessage(a.Request.Message.Replace("request", "response")); }) .UsingChannelClosedHandler((sender, a) => { Console.WriteLine("channel closed"); }) .Go(); var clientCommunication = new TcpCommunication <StringMessage>( new TcpEndpointData(IPAddress.Loopback, 2000), serializer); var r = Scenarios.RequestResponse.Requester(clientCommunication); using (r.Channel) { r.Channel.Open(); for (int i = 0; i < 100; i++) { var requestMessage = new StringMessage($"request #{i}"); Console.WriteLine(requestMessage); var responseMessage = r.Request(requestMessage); Console.WriteLine(responseMessage); } r.Channel.Close(); } server.Stop(); Console.ReadKey(); }
static void Main(string[] args) { var serializer = new StringMessageSerializer(); var serverSubscribersCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2000), serializer); var serverPublishersCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2001), serializer); var clientSubscribersCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Loopback, 2000), serializer); var clientPublishersCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Loopback, 2001), serializer); var server = Scenarios.Bus.RunServer(serverSubscribersCommunication, serverPublishersCommunication); var client1 = Scenarios.Bus.SetupClient(clientSubscribersCommunication, clientPublishersCommunication) .UsingTopics(new[] { "first topic" }) .UsingMessageReceivedHandler((s, a) => { Console.WriteLine($"Client 1 received: {a.Message}"); }) .Go(); var client2 = Scenarios.Bus.SetupClient(clientSubscribersCommunication, clientPublishersCommunication) .UsingTopics(new[] { "second topic" }) .UsingMessageReceivedHandler((s, a) => { Console.WriteLine($"Client 2 received: {a.Message}"); }) .Go(); var client3 = Scenarios.Bus.SetupClient(clientSubscribersCommunication, clientPublishersCommunication) .UsingTopics(new[] { "second topic" }) .UsingMessageReceivedHandler((s, a) => { Console.WriteLine($"Client 3 received: {a.Message}"); }) .Go(); client1.Publish("second topic", new StringMessage("message for second topic")); client2.Publish("first topic", new StringMessage("message for first topic")); Console.ReadKey(); client1.Close(); client2.Close(); client3.Close(); }
public DebugSession(DebugClient debugClient, ApplicationType type, Socket socket) { Client = debugClient; this.type = type; communication = new TcpCommunication(socket); }
static void Main(string[] args) { Console.WriteLine("Press '1' for TCP transport"); Console.WriteLine("Press '2' for Intradomain transport"); var transport = RequestTransport(); Console.WriteLine(); var serializer = new StringMessageSerializer(); ICommunication <StringMessage> serverCommunication; if (transport == Transport.Tcp) { serverCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Any, 2000), serializer); } else { serverCommunication = new IntradomainCommunication <StringMessage>(new IntradomainEndpoint("test"), serializer); } var server = Scenarios.RequestResponse.SetupServer(serverCommunication) .UsingNewClientHandler((sender, a) => { Console.WriteLine("channel opened"); }) .UsingRequestHandler((sender, a) => { a.Response = new StringMessage(a.Request.Message.Replace("request", "response")); }) .UsingChannelClosedHandler((sender, a) => { Console.WriteLine("channel closed"); }) .Go(); ICommunication <StringMessage> clientCommunication; if (transport == Transport.Tcp) { clientCommunication = new TcpCommunication <StringMessage>(new TcpEndpointData(IPAddress.Loopback, 2000), serializer); } else { clientCommunication = new IntradomainCommunication <StringMessage>(new IntradomainEndpoint("test"), serializer); } var r = Scenarios.RequestResponse.Requester(clientCommunication); using (r.Channel) { r.Channel.Open(); var requester = new Requester(r.Channel); var requestMessage = new StringMessage($"request using {transport} transport"); Console.WriteLine(requestMessage); var responseMessage = requester.Request(requestMessage); Console.WriteLine(responseMessage); r.Channel.Close(); } server.Stop(); Console.ReadKey(); }
private JavaScriptObject send(HttpRequest request) { string DeviceNo = request["DeviceNo"] ?? ""; string k = request["k"] ?? ""; string content = request["content"] ?? ""; string DeviceTime = request["DeviceTime"] ?? ""; string YearExploitation = request["YearExploitation"] ?? ""; string SerialNumber = request["SerialNumber"] ?? ""; string Range = request["Range"] ?? ""; string LineLength = request["LineLength"] ?? ""; JavaScriptObject result = new JavaScriptObject(); result.Add("Result", false); result.Add("Message", ""); if (DeviceNo.Length != 15) { result["Message"] = "设备编号格式不对!"; return(result); } Device device = DeviceModule.GetDeviceByFullDeviceNo(DeviceNo); if (device == null) { result["Message"] = "设备编号不存在!" + DeviceNo; return(result); } try { bool waitRsp = false; TcpCommunication tcpService = new TcpCommunication(); int timeDelay = 0; //待socket准备好 while (timeDelay < tcpService.TcpWait) { if ((tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CONNECTED) || (tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CLOSED)) { break; } Thread.Sleep(100); timeDelay = timeDelay + 1; } if (tcpService.SOCKET_STATE != TcpCommunication.TCP_SocketState.SOCKET_CONNECTED) { result["Message"] = "与网关通讯失败!"; return(result); } byte[] cmd_send = null; if (k == "1") { CmdToDtuSetDateTime cmd = new CmdToDtuSetDateTime(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.DateTimeNew = DateTime.Parse(DeviceTime); cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "2") { CmdToDtuQueryDateTime cmd = new CmdToDtuQueryDateTime(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "3") { CmdToDtuSetYearExploitation cmd = new CmdToDtuSetYearExploitation(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.YearExploitation = decimal.Parse(YearExploitation); cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "4") { CmdToDtuQueryYearExploitation cmd = new CmdToDtuQueryYearExploitation(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "5") { CmdToDtuOpenPump cmd = new CmdToDtuOpenPump(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "6") { CmdToDtuClosePump cmd = new CmdToDtuClosePump(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "7") { CmdToDtuSetStationCode cmd = new CmdToDtuSetStationCode(); if (device.StationType == 0) { result["Message"] = "非主从站无法设置分站射频地址!"; return(result); } else if (device.StationType == 1) { cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; List <Device> DeviceSubList = DeviceModule.GetAllDeviceSubList(device.Id); List <int> list = new List <int>(); foreach (Device DeviceSub in DeviceSubList) { list.Add(DeviceSub.StationCode); } cmd.StationCodeList = list; } else if (device.StationType == 2) { Device DeviceMain = DeviceModule.GetDeviceByID(device.MainId); string DeviceMainNo = DeviceModule.GetFullDeviceNoByID(device.MainId); cmd.AddressField = DeviceMainNo.Substring(0, 12) + Convert.ToInt32(DeviceMainNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)DeviceMain.StationType; cmd.StationCode = DeviceMain.StationType == 2 ? DeviceMain.StationCode : 0; List <Device> DeviceSubList = DeviceModule.GetAllDeviceSubList(device.MainId); List <int> list = new List <int>(); foreach (Device DeviceSub in DeviceSubList) { list.Add(DeviceSub.StationCode); } cmd.StationCodeList = list; } cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "8") { if (SerialNumber.Length != 8) { result["Message"] = "卡号长度只能为8位!"; return(result); } if (!Regex.IsMatch(SerialNumber, "^[0-9A-Fa-f]+$")) { result["Message"] = "卡号只能为0-9A-Fa-f!"; return(result); } CmdToDtuShieldSerialNumber cmd = new CmdToDtuShieldSerialNumber(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.SerialNumber = SerialNumber; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "9") { if (SerialNumber.Length != 8) { result["Message"] = "卡号长度只能为8位!"; return(result); } if (!Regex.IsMatch(SerialNumber, "^[0-9A-Fa-f]+$")) { result["Message"] = "卡号只能为0-9A-Fa-f!"; return(result); } CmdToDtuShieldSerialNumberCancel cmd = new CmdToDtuShieldSerialNumberCancel(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.SerialNumber = SerialNumber; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "10") { CmdToDtuSetGroundWaterParam cmd = new CmdToDtuSetGroundWaterParam(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.Range = byte.Parse(Range); cmd.LineLength = double.Parse(LineLength); cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "11") { CmdToDtuQueryGroundWaterParam cmd = new CmdToDtuQueryGroundWaterParam(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "12") { CmdToDtuQueryGroundWater cmd = new CmdToDtuQueryGroundWater(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else if (k == "13") { CmdToDtuQueryState cmd = new CmdToDtuQueryState(); cmd.AddressField = DeviceNo.Substring(0, 12) + Convert.ToInt32(DeviceNo.Substring(12, 3)).ToString("X").PadLeft(2, '0'); cmd.StationType = (byte)device.StationType; cmd.StationCode = device.StationType == 2 ? device.StationCode : 0; cmd.RawDataChar = cmd.WriteMsg(); cmd.RawDataStr = HexStringUtility.ByteArrayToHexString(cmd.RawDataChar); myLogger.Info(cmd.RawDataStr); cmd_send = cmd.RawDataChar; } else { result["Message"] = "参数错误!"; return(result); } tcpService.SendData(cmd_send, 0, cmd_send.Length); timeDelay = 0; while (timeDelay < tcpService.TcpWait) { if (tcpService.socketData.Buffer.Length > 0) { myLogger.Info(HexStringUtility.ByteArrayToHexString(tcpService.socketData.Buffer.Buffer)); } if (tcpService.socketData.Buffer.Length >= CommandCommon.CMD_MIN_LENGTH) { byte[] re = tcpService.socketData.Buffer.Buffer; byte[] buffer_new = new byte[tcpService.socketData.Buffer.Length]; Array.Copy(re, buffer_new, tcpService.socketData.Buffer.Length); string receiveHex = HexStringUtility.ByteArrayToHexString(buffer_new); //string str = HexStringUtility.HexStringToStr(receiveHex); waitRsp = true; result["Result"] = true; if (receiveHex == BaseProtocol.DeviceOffline) { result["Message"] = "查询终端不在线"; } else { result["Message"] = "终端在线返回结果:" + receiveHex; } } if (waitRsp == true) { myLogger.Info("获取响应结束"); break; } if (tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CLOSED) { myLogger.Info("Socket关闭结束"); break; } Thread.Sleep(100); timeDelay = timeDelay + 1; } tcpService.Close(); if (waitRsp == false) { result["Message"] = "等待设备回复超时!"; } } catch (Exception exception) { result["Message"] = exception.Message; myLogger.Error(exception.Message); } return(result); }
private async void btnConnectAuto_Click(object sender, EventArgs e) { try { Context.InAutoMode = true; if (Helper.TraceEnabled) { Logger.InitLogger(true); _loggerTask = Task.Factory.StartNew(LoggerAction); } else { Logger.InitLogger(); _loggerTask = null; } var changedFilesList = new ThreadSafeList <CustomFileHash>(); var commandResponseBuffer = new BufferBlock <byte[]>(); var tcpClient = new TcpClient(txtHostAuto.Text, Int32.Parse(txtPortAuto.Text)); _tcpCommunication = new TcpCommunication(tcpClient, commandResponseBuffer, changedFilesList); var connectionBytes = Encoding.UTF8.GetBytes(txtUsername.Text + ":" + txtUserpassword.Text + ":"); _tcpCommunication.SendCommand(connectionBytes, 0, connectionBytes.Length); await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync(); var response = _tcpCommunication.CommandResponseBuffer.Receive(); var message = Encoding.UTF8.GetString(response).Split(':'); if (message[0].Equals("Error")) { MessageBox.Show(message[1], @"Invalid user or password"); _tcpCommunication.Dispose(); } else { SwitchAutoUiState(UiConnectedState); Context.CurrentUser = txtUsername.Text; _commandHandler = new CommandHandler(_tcpCommunication); Logger.WriteInitialSyncBreakLine(); var filesForInitialSync = await DetermineFilesForInitialSync(); _syncProcessor = new SyncProcessor(_commandHandler, changedFilesList); filesForInitialSync.ForEach(_syncProcessor.AddChangedFile); await _syncProcessor.ChangedFileManager(); Logger.WriteSyncBreakLine(); changedFilesList.OnAdd += changedFilesList_OnAdd; _myFsWatcher = new MyFsWatcher(txtDefaultFolderAuto.Text, _syncProcessor); } } catch (FormatException fex) { var str = "Message: " + fex.Message + "\nSource: " + fex.Source + "\nStackTrace: " + fex.StackTrace; MessageBox.Show(str, @"Syncroniser - FormatException"); SwitchAutoUiState(false); MessageBox.Show(fex.Message); } catch (Exception ex) { var str = "Message: " + ex.Message + "\nSource: " + ex.Source + "\nStackTrace: " + ex.StackTrace; MessageBox.Show(str, @"Syncroniser - Exception"); SwitchAutoUiState(false); MessageBox.Show(ex.Message); } }
private async void ManageUserLogin() { try { var changedFilesList = new ThreadSafeList <CustomFileHash>(); var commandResponseBuffer = new BufferBlock <byte[]>(); var tcpClient = EstablishTcpCommunication(); _tcpCommunication = new TcpCommunication(tcpClient, commandResponseBuffer, changedFilesList); var connectionBytes = Encoding.UTF8.GetBytes(_loginViewModel.UserName + ":" + _loginViewModel.UserPassword + ":"); _tcpCommunication.SendCommand(connectionBytes, 0, connectionBytes.Length); await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync(); var response = _tcpCommunication.CommandResponseBuffer.Receive(); var message = Encoding.UTF8.GetString(response).Split(':'); if (message[0].Equals("Error")) { _tcpCommunication.Dispose(); Messenger.Default.Send(new LoginFailedMsg()); MessageBox.Show(message[1], @"Datele de autentificare sunt invalide.", MessageBoxButton.OK, MessageBoxImage.Warning); } else { RaisePropertyChanged(() => ConnectedUserName); Logger.InitLogger(Helper.TraceEnabled); Logger.WriteInitialSyncBreakLine(); _commandHandler = new CommandHandler(_tcpCommunication); var filesForInitialSync = await DetermineFilesForInitialSync(); _syncProcessor = new SyncProcessor(_commandHandler, changedFilesList); filesForInitialSync.ForEach(_syncProcessor.AddChangedFile); SetupLayout(UiState.LoggedIn); Messenger.Default.Send(new LoginSuccededMsg()); await _syncProcessor.ChangedFileManager(); Logger.WriteSyncBreakLine(); changedFilesList.OnAdd += changedFilesList_OnAdd; _myFsWatcher = new MyFsWatcher(Helper.SyncLocation, _syncProcessor); } } catch (FormatException ex) { LoginVisibility = Visibility.Visible; Messenger.Default.Send(new LoginFailedMsg()); var str = "Message: " + ex.Message + "\nSource: " + ex.Source + "\nStackTrace: " + ex.StackTrace; MessageBox.Show(str, @"Sincronizator de fișiere - Excepție de formatare"); } catch (SocketException ex) { LoginVisibility = Visibility.Visible; Messenger.Default.Send(new LoginFailedMsg()); var str = "Message: " + ex.Message + "\nSource: " + ex.Source + "\nStackTrace: " + ex.StackTrace; MessageBox.Show(str, @"Sincronizator de fișiere - Excepție de socket"); } catch (Exception ex) { LoginVisibility = Visibility.Visible; Messenger.Default.Send(new LoginFailedMsg()); var str = "Message: " + ex.Message + "\nSource: " + ex.Source + "\nException Type: " + ex.GetType() + "\nStackTrace: " + ex.StackTrace; MessageBox.Show(str, @"Sincronizator de fișiere - Excepție"); } }
private ResMsg SendCmd(byte[] cmd_send) { ResMsg msg = new ResMsg(false, ""); try { TcpCommunication tcpService = new TcpCommunication(); int timeDelay = 0; //待socket准备好 while (timeDelay < tcpService.TcpWait) { if ((tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CONNECTED) || (tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CLOSED)) { break; } Thread.Sleep(100); timeDelay = timeDelay + 1; } if (tcpService.SOCKET_STATE != TcpCommunication.TCP_SocketState.SOCKET_CONNECTED) { msg.Message = "与网关通讯失败!"; return(msg); } tcpService.SendData(cmd_send, 0, cmd_send.Length); bool waitRsp = false; timeDelay = 0; while (timeDelay < tcpService.TcpWait) { if (tcpService.socketData.Buffer.Length >= CommandCommon.CMD_MIN_LENGTH) { byte[] re = tcpService.socketData.Buffer.Buffer; byte[] buffer_new = new byte[tcpService.socketData.Buffer.Length]; Array.Copy(re, buffer_new, tcpService.socketData.Buffer.Length); waitRsp = true; msg.Result = true; msg.Message = HexStringUtility.ByteArrayToHexString(buffer_new); myLogger.Info("收到数据:" + msg.Message); } if (waitRsp == true) { //myLogger.Info("获取响应结束"); break; } if (tcpService.SOCKET_STATE == TcpCommunication.TCP_SocketState.SOCKET_CLOSED) { //myLogger.Info("Socket关闭结束"); break; } Thread.Sleep(50); timeDelay = timeDelay + 1; } tcpService.Close(); if (waitRsp == false) { msg.Message = "等待设备回复超时!"; } } catch (Exception e) { myLogger.Info("异常信息为:" + e.StackTrace); } return(msg); }
public ClientSession(Socket socket) { directoryName = Path.Combine(root, Path.GetRandomFileName()); remoteEndpoint = ((IPEndPoint)socket.RemoteEndPoint).Address; communication = new TcpCommunication(socket); }