static void RunTest () { // Start the server thread ServerThread serverThread = new ServerThread (); serverThread.Start (); // Create the client HttpWebRequest rq = (HttpWebRequest) WebRequest.Create ("http://" + IPAddress.Loopback.ToString () + ":54321"); rq.ProtocolVersion = HttpVersion.Version11; rq.KeepAlive = false; // Get the response HttpWebResponse rsp = (HttpWebResponse) rq.GetResponse (); ASCIIEncoding enc = new ASCIIEncoding (); StringBuilder result = new StringBuilder (); // Stream the body in 1 byte at a time byte [] bytearr = new byte [1]; Stream st = rsp.GetResponseStream (); while (true) { int b = st.Read (bytearr, 0, 1); if (b == 0) { break; } result.Append (enc.GetString (bytearr)); } Assert.AreEqual ("012345670123456789abcdefabcdefghijklmnopqrstuvwxyz", result.ToString (), "#1"); }
private void HandleClientComm(object client) { tcp_client = (TcpClient)client; NetworkStream client_stream = tcp_client.GetStream(); byte[] message = new byte[2048]; int bytes_read; while(isTrue == true) { bytes_read = 0; try { //blocks until a client sends a message bytes_read = client_stream.Read(message, 0, 2048); //Debug.Log(message); } catch (Exception e) { //a socket error has occured Debug.Log(e.Message); break; } if(bytes_read == 0) { //client has disconnected Debug.Log("Disconnected"); tcp_client.Close(); break; } ASCIIEncoding encoder = new ASCIIEncoding(); String msg = encoder.GetString(message,0,bytes_read); //Debug.Log(msg); String[] nums = msg.Split('!'); float x,y,z; if (nums.Length==3) { x = float.Parse(nums[0], CultureInfo.InvariantCulture.NumberFormat); y = float.Parse(nums[1], CultureInfo.InvariantCulture.NumberFormat); z = float.Parse(nums[2], CultureInfo.InvariantCulture.NumberFormat); Vector3 newPos = new Vector3(x,y,z); player.changePos(newPos); } else { tcp_client.GetStream().Close(); tcp_client.Close(); } } if(isTrue == false) { tcp_client.Close(); Debug.Log("closing tcp client"); } }
/** * This function returns a serialized JSON string representation of the object provided. */ public static string SerializeObjectToJSON(Object obj) { ASCIIEncoding encoding = new ASCIIEncoding(); MemoryStream memStream = new MemoryStream(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); serializer.WriteObject(memStream, obj); string result = encoding.GetString(memStream.GetBuffer()).ToString(); result = result.Substring(0, 1 + result.LastIndexOf('}')); return result; }
private void HandleClientComm(object client) { tcp_client = (TcpClient)client; NetworkStream client_stream = tcp_client.GetStream(); byte[] message = new byte[4096]; int bytes_read; while(isTrue == true) { bytes_read = 0; //blocks until a client sends a message bytes_read = client_stream.Read(message, 0, 4096); //Debug.Log(message); //a socket error has occured if(bytes_read == 0) { //client has disconnected Debug.Log("Disconectado"); tcp_client.Close(); break; } ASCIIEncoding encoder = new ASCIIEncoding(); Debug.Log(encoder.GetString(message,0,bytes_read)); comand = encoder.GetString(message,0,bytes_read); } if(isTrue == false) { tcp_client.Close(); Debug.Log("Conexao TCP terminada"); clientThread.Abort(); listen_thread.Abort(); tcp_listener.Stop(); Debug.Log("clientThread: " + clientThread.IsAlive); Debug.Log("listen_thread: " + clientThread.IsAlive); } }
public static string NextString(this Random r, int length) { var data = new byte[length]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)r.Next(35, 150); } var encoding = new ASCIIEncoding(); return encoding.GetString(data); }
private void HandleClientComm(object client) { tcp_client = (TcpClient)client; // variavel "tcp_client" recebe o objeto passado por parametro "client" NetworkStream client_stream = tcp_client.GetStream (); // Criacao de uma Stream, para ler a mensagem byte[] message = new byte[4096];// criacao de um array de bytes para ler a mensagem a receber int bytes_read; //Controlar o numero de bytes lidos na mensagem recebida while (isTrue == true) { bytes_read = 0; bytes_read = client_stream.Read (message, 0, 4096); //Bloqueia ate que cliente envie uma mensagem //Caso ocorra um errro no Socket, termina a ligacao com o client if (bytes_read == 0) { Debug.Log ("Disconectado"); connect = false; tcp_client.Close (); break; } ASCIIEncoding encoder = new ASCIIEncoding (); // Descodificacao ASCII da mensagem recebida Debug.Log (encoder.GetString (message, 0, bytes_read)); comand = encoder.GetString (message, 0, bytes_read); // string que guardara com mensagem recebida RecebeuComando = true; } }
/// <summary> /// Generates random string of printable ASCII symbols of a given length /// </summary> /// <param name="r">instance of the Random class</param> /// <param name="length">length of a random string</param> /// <returns>Random string of a given length</returns> public static string NextString(this Random r, int length) { var data = new byte[length]; for (int i = 0; i < data.Length; i++) { // All ASCII symbols: printable and non-printable // data[i] = (byte)r.Next(0, 128); // Only printable ASCII data[i] = (byte)r.Next(32, 127); } var encoding = new ASCIIEncoding(); return encoding.GetString(data); }
private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { //a socket error has occured break; } if (bytesRead == 0) { //the client has disconnected from the server break; } //message has successfully been received ASCIIEncoding encoder = new ASCIIEncoding(); String message_string = encoder.GetString(message, 0, bytesRead); CallResponse call_response = new CallResponse(message_string, clientStream); queue.add(call_response); } tcpClient.Close(); }
// Purpose: Connect to node.js application (lamechat.js) // End Result: node.js app now has a socket open that can send // messages back to this tcp client application private void cmdConnect_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(txtChatName.Text)) { this.txtConversation.Text += "Please input your name.\n"; return; } try { if (tcpClient.Connected == true) { TcpClient tcpClient = new TcpClient(); tcpClient.Connect("10.60.250.150", 4000); serverStream = tcpClient.GetStream(); AddPrompt(); byte[] outStream = Encoding.ASCII.GetBytes(txtChatName.Text.Trim() + " is reconnecting"); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); } else { tcpClient.Connect("10.60.250.150", 4000); serverStream = tcpClient.GetStream(); AddPrompt(); byte[] outStream = Encoding.ASCII.GetBytes(txtChatName.Text.Trim() + " is joining"); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); } } catch (Exception) { this.txtConversation.Text += "Can't connect. Reason can be :\r\n1.Server is down.\r\n2.You lost internet connection\n"; return; } // upload as javascript blob Task taskOpenEndpoint = Task.Factory.StartNew(() => { while (true) { // Read bytes serverStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; bytesRead = 0; try { // Read up to 4096 bytes bytesRead = serverStream.Read(message, 0, 4096); } catch { /*a socket error has occured*/ } //We have rad the message. ASCIIEncoding encoder = new ASCIIEncoding(); // Update main window AddMessage(encoder.GetString(message, 0, bytesRead)); Thread.Sleep(500); } }); }
/// <summary> /// Read the next 512 byte chunk of data as a tar header. /// </summary> /// <returns>A tar header structure. null if we have reached the end of the archive.</returns> protected TarHeader ReadHeader() { byte [] header = m_br.ReadBytes(512); // If there are no more bytes in the stream, return null header if (header.Length == 0) { return(null); } // If we've reached the end of the archive we'll be in null block territory, which means // the next byte will be 0 if (header [0] == 0) { return(null); } TarHeader tarHeader = new TarHeader(); // If we're looking at a GNU tar long link then extract the long name and pull up the next header if (header [156] == (byte)'L') { int longNameLength = ConvertOctalBytesToDecimal(header, 124, 11); tarHeader.FilePath = m_asciiEncoding.GetString(ReadData(longNameLength)); //MainConsole.Instance.DebugFormat("[TAR ARCHIVE READER]: Got long file name {0}", tarHeader.FilePath); header = m_br.ReadBytes(512); } else { tarHeader.FilePath = m_asciiEncoding.GetString(header, 0, 100); tarHeader.FilePath = tarHeader.FilePath.Trim(m_nullCharArray); //MainConsole.Instance.DebugFormat("[TAR ARCHIVE READER]: Got short file name {0}", tarHeader.FilePath); } tarHeader.FileSize = ConvertOctalBytesToDecimal(header, 124, 11); switch (header [156]) { case 0: tarHeader.EntryType = TarEntryType.TYPE_NORMAL_FILE; break; case (byte)'0': tarHeader.EntryType = TarEntryType.TYPE_NORMAL_FILE; break; case (byte)'1': tarHeader.EntryType = TarEntryType.TYPE_HARD_LINK; break; case (byte)'2': tarHeader.EntryType = TarEntryType.TYPE_SYMBOLIC_LINK; break; case (byte)'3': tarHeader.EntryType = TarEntryType.TYPE_CHAR_SPECIAL; break; case (byte)'4': tarHeader.EntryType = TarEntryType.TYPE_BLOCK_SPECIAL; break; case (byte)'5': tarHeader.EntryType = TarEntryType.TYPE_DIRECTORY; break; case (byte)'6': tarHeader.EntryType = TarEntryType.TYPE_FIFO; break; case (byte)'7': tarHeader.EntryType = TarEntryType.TYPE_CONTIGUOUS_FILE; break; } return(tarHeader); }
private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); string filename = "empty"; byte[] message = new byte[tcpClient.ReceiveBufferSize]; int bytesRead; { bytesRead = 0; { bytesRead = clientStream.Read(message, 0, tcpClient.ReceiveBufferSize); string headerstring = encoder.GetString(message, 0, bytesRead); int filepathlength = message[0]; filename = headerstring.Substring(1, filepathlength - 1); } Console.WriteLine("filename=" + filename); } while (true) { using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Yoloswag\\Desktop\\stevenftp\\received\\" + filename, true)) { try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, tcpClient.ReceiveBufferSize); file.Write(message); } catch { //a socket error has occured break; } if (bytesRead == 0) { //the client has disconnected from the server break; } //message has successfully been received if (message.Equals(StevenFileSendTelemetry.terminalBoy)) { Console.WriteLine("Terminal string received -- Done reading file"); break; } //Console.WriteLine(encoder.GetString(message, 0, bytesRead)); if (bytesRead != 0) { break; } } } TalkBackToClient(tcpClient); tcpClient.Close(); }
// // CallRestAPIFiles submits an API request to the FogBugz api using the // multipart/form-data submission method (so you can add files) // Don't forget to include nFileCount in your rgArgs collection if you are adding files. // private string CallRESTAPIFiles(string sURL, Dictionary <string, string> rgArgs, Dictionary <string, byte[]>[] rgFiles) { string sBoundaryString = getRandomString(30); string sBoundary = "--" + sBoundaryString; ASCIIEncoding encoding = new ASCIIEncoding(); UTF8Encoding utf8encoding = new UTF8Encoding(); HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(sURL); http.Method = "POST"; http.AllowWriteStreamBuffering = true; http.ContentType = "multipart/form-data; boundary=" + sBoundaryString; const string vbCrLf = "\r\n"; Queue parts = new Queue(); // // add all the normal arguments // foreach (System.Collections.Generic.KeyValuePair <string, string> i in rgArgs) { parts.Enqueue(encoding.GetBytes(sBoundary + vbCrLf)); parts.Enqueue(encoding.GetBytes("Content-Type: text/plain; charset=\"utf-8\"" + vbCrLf)); parts.Enqueue(encoding.GetBytes("Content-Disposition: form-data; name=\"" + i.Key + "\"" + vbCrLf + vbCrLf)); parts.Enqueue(utf8encoding.GetBytes(i.Value)); parts.Enqueue(encoding.GetBytes(vbCrLf)); } // // add all the files // if (rgFiles != null) { foreach (Dictionary <string, byte[]> j in rgFiles) { parts.Enqueue(encoding.GetBytes(sBoundary + vbCrLf)); parts.Enqueue(encoding.GetBytes("Content-Disposition: form-data; name=\"")); parts.Enqueue(j["name"]); parts.Enqueue(encoding.GetBytes("\"; filename=\"")); parts.Enqueue(j["filename"]); parts.Enqueue(encoding.GetBytes("\"" + vbCrLf)); parts.Enqueue(encoding.GetBytes("Content-Transfer-Encoding: base64" + vbCrLf)); parts.Enqueue(encoding.GetBytes("Content-Type: ")); parts.Enqueue(j["contenttype"]); parts.Enqueue(encoding.GetBytes(vbCrLf + vbCrLf)); parts.Enqueue(j["data"]); parts.Enqueue(encoding.GetBytes(vbCrLf)); } } parts.Enqueue(encoding.GetBytes(sBoundary + "--")); // // calculate the content length // int nContentLength = 0; foreach (Byte[] part in parts) { nContentLength += part.Length; } http.ContentLength = nContentLength; // // write the post // Stream stream = http.GetRequestStream(); string sent = ""; foreach (Byte[] part in parts) { stream.Write(part, 0, part.Length); sent += encoding.GetString(part); } stream.Close(); // // read the result // Stream r = http.GetResponse().GetResponseStream(); StreamReader reader = new StreamReader(r); string retValue = reader.ReadToEnd(); reader.Close(); if (ApiCalled != null) { ApiCalled(this, sent, retValue); } return(retValue); }
public static T ConvertByteArrayToObject <T>(byte[] param) { return(DeserializeRequest <T>(encoder.GetString(param))); }
public bool Connect(string address, int port, string token, ControllerPermissions permissions, int receiveTimeout = 1000) { Disconnect(); lock (m_dataQueueLock) { m_dataQueue = new Queue<byte[]>(); } try { lock (m_lock) { m_client = new TcpClient(); m_client.ReceiveTimeout = receiveTimeout; m_client.NoDelay = true; m_client.Connect(address, port); if (token.Length < TOKEN_SIZE) for (int i = token.Length; i < TOKEN_SIZE; ++i) token += " "; else if (token.Length > TOKEN_SIZE) token = token.Substring(0, TOKEN_SIZE); var stream = m_client.GetStream(); var ascii = new ASCIIEncoding(); var tokenBytes = ascii.GetBytes(token); stream.Write(tokenBytes, 0, tokenBytes.Length); stream.Write(BitConverter.GetBytes((Int32)permissions), 0, 4); tokenBytes = new byte[TOKEN_SIZE]; var tokenSize = stream.Read(tokenBytes, 0, TOKEN_SIZE); if (tokenSize == TOKEN_SIZE) { lock (m_camerasListLock) { m_camerasList = new List<string>(); } m_token = ascii.GetString(tokenBytes); m_permissions = permissions; SpawnCommandsReceiverTask(); SpawnCommandsExecutorTask(); return true; } } } catch { } Disconnect(); return false; }
/// <summary> /// ASCII字符编码数组转换为字符串 /// </summary> /// <param name="input">ASCII字符编码数组</param> /// <returns>ASCII字符编码数组转换后的字符串</returns> public static string ASCIIBytesToString(this byte[] input) { System.Text.ASCIIEncoding enc = new ASCIIEncoding(); return(enc.GetString(input)); }
/* * Helper Function to keep character creation clean and then send the information to the server. */ static void characterCreationLogin(Socket serverSocket) { string login; string serverSalt = ""; bool saltArrived = false; ConsoleKeyInfo passwordInterceptor; StringBuilder password = new StringBuilder(); bool loginCompleted = false; while (loginCompleted == false) { Console.WriteLine("Please Login"); Console.WriteLine("Your User name can be up to 20 characters long."); Console.WriteLine("Your User name cannot contain any special characters."); login = Console.ReadLine(); Console.Clear(); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] logindetails = encoder.GetBytes(login); try { int bytesSent = serverSocket.Send(logindetails); } catch (System.Exception ex) { Console.WriteLine(ex); } while (saltArrived == false) { try { byte[] buffer = new byte[4096]; int result; result = serverSocket.Receive(buffer); if (result > 0) { serverSalt = encoder.GetString(buffer, 0, result); saltArrived = true; } } catch (Exception ex) { Console.Clear(); Console.WriteLine("Waiting for Server Response"); } } Console.WriteLine("Please enter your password"); Console.WriteLine("Your password will be hidden while typing"); passwordInterceptor = Console.ReadKey(true); while (passwordInterceptor.Key != ConsoleKey.Enter) { password.Append(passwordInterceptor.KeyChar); passwordInterceptor = Console.ReadKey(true); } Console.Clear(); loginCompleted = SpecialCharacterCheck(login); loginCompleted = SpecialCharacterCheck(password.ToString()); if (loginCompleted == true) { byte[] userdetails = encoder.GetBytes(login); try { string stringword = password.ToString(); login += " " + GenerateSaltedHash(encoder.GetBytes(stringword), encoder.GetBytes(serverSalt)) + " " + serverSalt.ToString(); logindetails = encoder.GetBytes(login); int bytesSent = serverSocket.Send(logindetails); } catch (System.Exception ex) { Console.WriteLine(ex); } } } }
private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; tcpClient.NoDelay = true; clientStream = tcpClient.GetStream(); encoder = new ASCIIEncoding(); //byte[] buffer = encoder.GetBytes("Hello Client!"); //clientStream.Write(buffer, 0, buffer.Length); //clientStream.Flush(); String xmlSheet; byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { //a socket error has occured break; } if (bytesRead == 0 || disconect == true) { //the client has disconnected from the server break; } //message has successfully been received xmlSheet = encoder.GetString(message, 0, bytesRead); String[] split = xmlSheet.Split(new String[] { "</DATA>" }, StringSplitOptions.None); String toDeserialize =split[0]+"</DATA>"; StringReader sReader = new StringReader(toDeserialize); data = (DATA)XMLseri.Deserialize(sReader); //Debug.Log("x"); //Debug.Log(data.x); //Debug.Log("y"); //Debug.Log(data.y); //Debug.Log("z"); //Debug.Log(data.z); //Debug.Log("w"); //Debug.Log(data.w); //Debug.Log(data.go); //Debug.Log(data.shield); } tcpClient.Close(); Debug.Log("Disconnected"); }
public static int viRead(int vi, out string asciiResults, int maxCount) { asciiResults = string.Empty; int retCount = 0; byte[] byteResults = new byte[maxCount]; int retVal = viRead(vi, byteResults, maxCount, out retCount); if (retVal >= visa32.VI_SUCCESS) { ASCIIEncoding encoding = new ASCIIEncoding(); asciiResults = encoding.GetString(byteResults, 0, retCount); } return retVal; }
private void HandleClientComm(object client) { //Debug.Log ("Called HandleClientComm, applicationRunning is: " + applicationRunning.ToString()); FileLogger.Log("New TCP Client accepted."); TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; while (applicationRunning) { bytesRead = 0; String message_string = ""; try { do { FileLogger.Log("About to block, waiting for Java."); //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); if(bytesRead == 0){ throw new Exception(""); } FileLogger.Log("Unblocked. Got bytes from Java."); ASCIIEncoding encoder = new ASCIIEncoding(); message_string += encoder.GetString(message, 0, bytesRead); } while (!message_string.EndsWith ("\n")); } catch(Exception e) { FileLogger.Log("A socket error occured or there was not data while waiting for Java: " + e.Message); //a socket error has occured break; } /*if (bytesRead == 0) { FileLogger.Log("The Java client disconnected"); //the client has disconnected from the server break; }*/ //message has successfully been received //ASCIIEncoding encoder = new ASCIIEncoding(); //String message_string = encoder.GetString(message, 0, bytesRead); //} //ends while loop FileLogger.Log("Unity got response from Java: "+message_string); CallResponse call_response = new CallResponse(message_string, clientStream); queue.add(call_response); } FileLogger.Log("Closing TCP connection."); //Debug.Log ("Closing TCP connection, applicationRunning is: " + applicationRunning.ToString()); tcpClient.Close(); }
public static string receivestring(Socket bacon, formConsole Console, ASCIIEncoding encoding) { StringBuilder data = new StringBuilder(); byte[] nomnom = new byte[bacon.ReceiveBufferSize]; Console.Write("Receiving."); while (bacon.Available > 0) { bacon.Receive(nomnom); data.Append(encoding.GetString(nomnom).Replace("\0", "")); Console.Write("."); } Console.WriteLine("!\nReceived: " + data.ToString()); return data.ToString(); }
private void SpawnCommandsExecutorTask() { Task.Run(() => { while (m_running) { byte[] data = null; lock (m_dataQueueLock) { data = m_dataQueue.Count > 0 ? m_dataQueue.Dequeue() : null; } if (data != null) { using (var stream = new MemoryStream(data)) using (var bs = new BinaryReader(stream)) { try { var type = (MessageType)bs.ReadInt32(); if (type == MessageType.ReceiveImage) { var w = bs.ReadInt32(); var h = bs.ReadInt32(); var c = bs.ReadInt32(); var d = bs.ReadBytes(w * h * c); lock (m_imageLock) { m_image = new ImageData(w, h, c, d); } lock (m_OnReceiveImageLock) { if (OnReceiveImage != null) OnReceiveImage(this, new EventArgs()); } } else if (type == MessageType.ObtainCamerasList) { var ascii = new ASCIIEncoding(); var count = bs.ReadInt32(); lock (m_camerasListLock) { m_camerasList = new List<string>(); for (var i = 0; i < count; ++i) m_camerasList.Add(ascii.GetString(bs.ReadBytes(TOKEN_SIZE))); } lock (m_OnObtainCamerasListLock) { if (OnObtainCamerasList != null) OnObtainCamerasList(this, new EventArgs()); } } } catch { } } } else Thread.Sleep(50); } lock (m_lock) { lock (m_dataQueueLock) { m_dataQueue = null; } } }); }
protected void loginBtn_Click(object sender, EventArgs e) { if (Request.Form["username"] != null && Request.Form["psw"] != null) { #region read User Inputs String userName = Request.Form["username"].ToString(); // "al.mahmoud"; // Environment.UserName; String Password = Request.Form["psw"].ToString(); //"Sharkas83@gmail"; String Selectedomain = selectedDomain.Value; //Request.Form["selectedDomain"].ToString(); Boolean validUser = IsValidUser(userName, Password); using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true)) { _testData.WriteLine(userName + " " + Password + " " + validUser.ToString()); } #endregion read User Inputs if (validUser) { //Response.Write("Valid User !!!!"); var user = (from users in db.Saml where users.username == userName && users.IsActive == true && users.logoutDate == null select users).FirstOrDefault(); if (user == null) // User Doesn't have Valid Authentication Session { #region Generate SAML Response //String certFile = @"C:\Users\afawzi\documents\visual studio 2017\Projects\saml\IdentityProvider\X509Certificate.cer"; String certFile = Server.MapPath("~/X509Certificate.cer"); String Issuer = "Idp_Mohammed_Tahtamouni"; int AssertionExpirationMinutes = 5; String Audience = Session["returnURL"].ToString(); //"http://*****:*****@"<body onload='document.forms[""form""].submit()'>"); sb.AppendFormat("<form name='form' action='{0}' method='post'>", Recipient); sb.AppendFormat("<input type='hidden' name='SAMLAssertion' value='{0}'>", SAMLAssertion); sb.Append("</form>"); sb.Append("</body>"); sb.Append("</html>"); Response.Write(sb.ToString()); Response.End(); } catch (Exception ex) { Response.Write(ex.ToString()); } #endregion POST to Service Provider } } else { // Show error Message } } }
public String decrypt(String strText) { ASCIIEncoding textConverter = new ASCIIEncoding(); string roundtrip; byte[] fromEncrypt; byte[] encrypted; //Encrypt the data. TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); ICryptoTransform decryptor = tdes.CreateDecryptor(encKey, initVec); int discarded; encrypted = HexEncoding.GetBytes(strText, out discarded); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); fromEncrypt = new byte[encrypted.Length]; //Read the data out of the crypto stream. csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); //Convert the byte array back into a string. roundtrip = textConverter.GetString(fromEncrypt); return (roundtrip.Replace("\0", "")); }
static string GetTextFromBytes(byte[] bytes, int start, int length) { return(ascii.GetString(bytes, start, length).TrimEnd('\0')); }
// Bytes are string public static string ASCIIBytesToString(byte[] input_in) { System.Text.ASCIIEncoding _enc = new ASCIIEncoding(); return(_enc.GetString(input_in)); }
private void HandleClientComm(object client) { Debug.Log ("Client Connect"); TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { //a socket error has occured break; } if (bytesRead == 0) { //the client has disconnected from the server break; } //message has successfully been received ASCIIEncoding encoder = new ASCIIEncoding(); //System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); //Command may contain more than 1 command string commandStr = encoder.GetString(message, 0, bytesRead); //Debug.Log("Get Command:"+commandStr); //split command char[] splitChar = {'{'}; string[] results = commandStr.Split(splitChar); //get all command in command Str for(int i = 1;i<results.Length;i++){ results[i] = splitChar[0]+results[i]; //Debug.Log("Get Command split:"+results[i]); //parse to json object JSONObject commandJsonObject = new JSONObject(results[i]); //push to command list if(commandJsonObject!=null){ commandList.Add (commandJsonObject); } } } //tcpClient.Close(); }
private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); int bytesRead; byte[] buffer = new byte[4096]; byte[] message = new byte[4096]; byte[] fileByte = File.ReadAllBytes(file); int intValue; string strValue; while (true) { bytesRead = 0; try { // Assuming that the client is sending a message bytesRead = clientStream.Read(message, 0, 4096); } catch { // A socker error has occured MessageBox.Show("An error has occured when trying to connect to the client... 0x01", "Error: 0x01"); break; } if (bytesRead == 0) { // The client has disconnected or didn't send any message MessageBox.Show("The client has disconnected... 0x02", "Error: 0x02"); break; } // A message has been received.. We should validate it now string msg = encoder.GetString(message).Replace("\0", ""); switch (msg) { case "HELLO": buffer = encoder.GetBytes("HELLO"); clientStream.Write(buffer, 0, buffer.Length); break; case "GETFILESIZE": intValue = fileByte.Length; strValue = Convert.ToString(intValue); char[] charValue = strValue.ToCharArray(); byte[] byteValue = encoder.GetBytes(charValue, 0, charValue.Length); clientStream.Write(byteValue, 0, byteValue.Length); break; case "GETFILENAME": buffer = encoder.GetBytes(filenameext); clientStream.Write(buffer, 0, buffer.Length); break; case "GETFILECONTENTS": clientStream.Write(fileByte, 0, fileByte.Length); break; case "CLOSETHECONNECTION": buffer = encoder.GetBytes("CLOSED"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Close(); tcpClient.Close(); Thread.CurrentThread.Abort(); break; default: MessageBox.Show("Unknown command received from the client... 0x03", "Error: 0x03"); break; } } }
public static string DESDecrypt(string Text, string sKey) { byte[] bufferEncrypted = ASCIIEncoding.ASCII.GetBytes(Text); MemoryStream StreamEncrypted = new MemoryStream(bufferEncrypted); DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desdecrypt = DES.CreateDecryptor(); CryptoStream cryptostreamDecr = new CryptoStream(StreamEncrypted, desdecrypt, CryptoStreamMode.Read); byte[] tors = new byte[StreamEncrypted.Length]; cryptostreamDecr.Read(tors, 0, tors.Length); // StreamReader sreader = new StreamReader(cryptostreamDecr); // string rs = sreader.ReadToEnd(); cryptostreamDecr.Close(); StreamEncrypted.Close(); //sreader.Close(); ASCIIEncoding ByteConverter = new ASCIIEncoding(); return ByteConverter.GetString(tors); //return rs; }
public static void Main() { long rv; long sid; rv = Api.saHpiSessionOpen( HpiConst.SAHPI_UNSPECIFIED_DOMAIN_ID, out sid, null ); if ( rv != HpiConst.SA_OK ) { Console.WriteLine( "Error: saHpiSessionOpen: {0}", rv ); return; } long last_hid = HpiConst.SAHPI_LAST_ENTRY; // List all handlers ASCIIEncoding ascii = new ASCIIEncoding(); foreach ( long hid in OhpiIterators.HandlerIds( sid ) ) { last_hid = hid; Console.WriteLine( "Handler {0}", hid ); oHpiHandlerInfoT hinfo; oHpiHandlerConfigT hconf; rv = Api.oHpiHandlerInfo( sid, hid, out hinfo, out hconf ); if ( rv != HpiConst.SA_OK ) { Console.WriteLine( "Error: oHpiHandlerInfo: {0}", rv ); continue; } Console.WriteLine( " Info" ); Console.WriteLine( " id {0}", hinfo.id ); Console.WriteLine( " name {0}", ascii.GetString( hinfo.plugin_name ) ); Console.WriteLine( " entity_root {0}", HpiUtil.FromSaHpiEntityPathT( hinfo.entity_root ) ); Console.WriteLine( " load_failed {0}", hinfo.load_failed ); Console.WriteLine( " Config" ); foreach ( var kv in OhpiUtil.FromoHpiHandlerConfigT( hconf ) ) { Console.WriteLine( " {0} = {1}", kv.Key, kv.Value ); } } // Retry last handler if ( last_hid != HpiConst.SAHPI_LAST_ENTRY ) { Console.WriteLine( "Re-trying last handler: {0}", last_hid ); rv = Api.oHpiHandlerRetry( sid, last_hid ); if ( rv != HpiConst.SA_OK ) { Console.WriteLine( "Error: oHpiHandlerRetry: {0}", rv ); } } // Destroy last handler if ( last_hid != HpiConst.SAHPI_LAST_ENTRY ) { Console.WriteLine( "Destroying last handler: {0}", last_hid ); rv = Api.oHpiHandlerDestroy( sid, last_hid ); if ( rv != HpiConst.SA_OK ) { Console.WriteLine( "Error: oHpiHandlerDestroy: {0}", rv ); } } // Look for handler providing specified resource { long hid = HpiConst.SAHPI_LAST_ENTRY; long rid = 5; rv = Api.oHpiHandlerFind( sid, rid, out hid ); if ( rv != HpiConst.SA_OK ) { Console.WriteLine( "Error: oHpiHandlerFind: {0}", rv ); } if ( hid != HpiConst.SAHPI_LAST_ENTRY ) { Console.WriteLine( "Resource {0} is provided by handler {1}", rid, hid ); } } // Create new instance of test_agent plugin { Console.WriteLine( "Creating new handler" ); var d = new Dictionary<String, String> { { "plugin", "libtest_agent" }, { "port" , "9999" } }; var hconf = OhpiUtil.TooHpiHandlerConfigT( d ); long hid; rv = Api.oHpiHandlerCreate( sid, hconf, out hid ); if ( rv == HpiConst.SA_OK ) { Console.WriteLine( "Created handler {0}", hid ); } else { Console.WriteLine( "Error: oHpiHandlerCreate: {0}", rv ); } } rv = Api.saHpiSessionClose( sid ); if ( rv != HpiConst.SA_OK ) { Console.WriteLine( "Error: saHpiSessionClose: {0}", rv ); return; } }
/// <summary> /// DEC�����㷨 /// </summary> /// <param name="Text">Must be over 64 bits, 8 bytes.</param> /// <param name="sKey">Must be 64 bits, 8 bytes.</param> /// <returns>���ܺ���ַ�</returns> public static string DESEncrypt(string Text, string sKey) { byte[] bufferToEncrypt = ASCIIEncoding.ASCII.GetBytes(Text); MemoryStream StreamEncrypted = new MemoryStream(); DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = DES.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(StreamEncrypted, desencrypt, CryptoStreamMode.Write); cryptostream.Write(bufferToEncrypt, 0, bufferToEncrypt.Length); //Convert it to string //byte[] tors = StreamEncrypted.GetBuffer(); byte[] tors = StreamEncrypted.ToArray(); //StreamReader sreader = new StreamReader(StreamEncrypted); //string rs = sreader.ReadToEnd(); cryptostream.Close(); StreamEncrypted.Close(); //sreader.Close(); ASCIIEncoding ByteConverter = new ASCIIEncoding(); return ByteConverter.GetString(tors); //return rs; }
/// <summary> /// The heartbeat thread for a client. This thread receives data from a client, /// closes the socket when it fails, and handles communication timeouts when /// the client does not send a heartbeat within 2x the heartbeat frequency. /// /// When the heartbeat is not received, the client is assumed to be unresponsive /// and the connection is closed. Waits for one ping to be received before /// enforcing the timeout. /// </summary> /// <param name="client">The client we are communicating with.</param> private void HeartbeatClient(object client) { mActiveClients.AddCount(); TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); mClients.Add(clientStream); ArrayList readList = new ArrayList(); bool heartbeatActive = false; byte[] message = new byte[4096]; ASCIIEncoding encoder = new ASCIIEncoding(); int length = 0; try { while (mRunning && tcpClient.Connected) { int bytesRead = 0; try { readList.Clear(); readList.Add(tcpClient.Client); if (mHeartbeat > 0 && heartbeatActive) { Socket.Select(readList, null, null, mHeartbeat * 2000); } if (readList.Count == 0 && heartbeatActive) { Console.WriteLine("Heartbeat timed out, closing connection\n"); break; } //blocks until a client sends a message bytesRead = clientStream.Read(message, length, 4096 - length); } catch (Exception e) { //a socket error has occured Console.WriteLine("Heartbeat read exception: " + e.Message + "\n"); break; } if (bytesRead == 0) { //the client has disconnected from the server Console.WriteLine("No bytes were read from heartbeat thread"); break; } // See if we have a line int pos = length; length += bytesRead; int eol = 0; for (int i = pos; i < length; i++) { if (message[i] == '\n') { String line = encoder.GetString(message, eol, i); if (Receive(clientStream, line)) { heartbeatActive = true; } eol = i + 1; } } // Remove the lines that have been processed. if (eol > 0) { length = length - eol; // Shift the message array to remove the lines. if (length > 0) { Array.Copy(message, eol, message, 0, length); } } } } catch (Exception e) { Console.WriteLine("Error during heartbeat: " + e.Message); } finally { try { mClients.Remove(clientStream); tcpClient.Close(); } catch (Exception e) { Console.WriteLine("Error during heartbeat cleanup: " + e.Message); } mActiveClients.Signal(); } }
public static int Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage : ReadFile <FileName>"); return 1; } if (! System.IO.File.Exists(args[0])) { Console.WriteLine("File " + args[0] + " not found."); return 1; } byte[] buffer = new byte[128]; FileReader fr = new FileReader(); if (fr.Open(args[0])) { // We are assuming that we are reading an ASCII file ASCIIEncoding Encoding = new ASCIIEncoding(); int bytesRead; do { bytesRead = fr.Read(buffer, 0, buffer.Length); string content = Encoding.GetString(buffer,0,bytesRead); Console.Write("{0}", content); } while ( bytesRead > 0); fr.Close(); return 0; } else { Console.WriteLine("Failed to open requested file"); return 1; } }
/// <summary> /// Converte array de bytes para string /// </summary> /// <param name="buffer">Buffer de entrada</param> /// <returns>String de saida</returns> private static string ConvertBytesToString(byte[] buffer) { ASCIIEncoding enc = new ASCIIEncoding(); return(enc.GetString(buffer)); }
// Update is called once per frame void Update() { width = Screen.width; height = Screen.height; gazePosNormalY = new Vector2(width/2, height/2); gazePosInvertY = gazePosNormalY; if(_client != null) { int size = _client.ReceiveBufferSize; byte[] received = new byte[size]; _client.GetStream().Read(received,0,size*sizeof(byte)); ASCIIEncoding encoding = new ASCIIEncoding(); string xmlString = encoding.GetString(received); Debug.Log(xmlString); xmlString = xmlString.Substring(0,xmlString.LastIndexOf(">")+1); xmlString = "<?xml version=\"1.0\"?><doc>" + xmlString; xmlString = xmlString.Insert(xmlString.LastIndexOf(">")+1,"</doc>"); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(xmlString); } catch(XmlException e) { print(e); print(xmlString); print(xmlString.Length); } XmlNode trackerNode = doc.SelectSingleNode("doc"); if(trackerNode != null && trackerNode.HasChildNodes) { trackerNode = trackerNode.LastChild; } if(trackerNode != null && trackerNode.Name == "ACK") { string id = trackerNode.Attributes["ID"].Value; string state = trackerNode.Attributes["STATE"].Value; if(id == "CALIBRATE_START") { _calibrating = state.Equals("1"); } } if(trackerNode != null && trackerNode.Name == "CALIB_RESULT_SUMMARY") { _calibrating = false; } if(trackerNode != null && trackerNode.Name == "REC") { string pogX = trackerNode.Attributes["BPOGX"].Value; string pogY = trackerNode.Attributes["BPOGY"].Value; string pogV = trackerNode.Attributes["BPOGV"].Value; gazePosValid = pogV.Equals("1")?true:false; if(gazePosValid) { gazePosNormalY = new Vector2((float.Parse(pogX) * width), (float.Parse(pogY)*height)-25); gazePosInvertY = new Vector2((float.Parse(pogX) * width), (height - float.Parse(pogY)*height)-25); gazePosNormalAveraging.Enqueue(gazePosNormalY); gazePosNormalYAveringTemp += gazePosNormalY; if(gazePosNormalAveraging.Count > 10) { Vector2 old = gazePosNormalAveraging.Dequeue(); gazePosNormalYAveringTemp-= old; gazePosNormalYAverage = gazePosNormalYAveringTemp/gazePosNormalAveraging.Count; } } } } }
static void ExecCmd(RemoteServer server, string cmd) { if (cmd == "iwim_heartbeat") { Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sendSocket.Bind(new IPEndPoint(IPAddress.Any, 32702)); Console.WriteLine("Sending heartbeat to server"); IPAddress sendTo = Dns.GetHostAddresses(server.HostName)[0]; IPEndPoint sendEndPoint = new IPEndPoint(sendTo, 32701); byte[] buffer = new byte[5]; buffer[0] = 2; buffer[1] = 0xFF; buffer[2] = 0xFF; buffer[3] = 0xFF; buffer[4] = 0xFF; sendSocket.SendTo(buffer, 5, SocketFlags.None, sendEndPoint); sendSocket.Close(); } if (cmd == "iwim_query_random" || cmd == "iwim_query_random_loop") { Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); int loops; if (cmd == "iwim_query_random") { loops = 1; } else { loops = 1000; } Console.WriteLine("Searching for {0} random assets starting {1}", loops, DateTime.Now); IPAddress sendTo = Dns.GetHostAddresses(server.HostName)[0]; IPEndPoint sendEndPoint = new IPEndPoint(sendTo, 32701); byte[] buffer = new byte[33]; buffer[0] = 0; for (int i = 0; i < loops; i++) { Guid guid = Guid.NewGuid(); string fguid = guid.ToString().Replace("-", ""); Array.Copy(Util.UuidToAscii(fguid), 0, buffer, 1, 32); sendSocket.SendTo(buffer, 33, SocketFlags.None, sendEndPoint); EndPoint recvEndpoint = new IPEndPoint(IPAddress.Any, sendEndPoint.Port); byte[] response = new byte[34]; sendSocket.ReceiveFrom(response, ref recvEndpoint); } Console.WriteLine("Done {0}", DateTime.Now); } if (cmd.Length > 10 && cmd.Substring(0, 10) == "iwim_query") { string uuid = cmd.Substring(11); Console.WriteLine("Asking for named asset " + uuid); server.GetAsset(uuid); } if (cmd == "getrandom") { Guid guid = Guid.NewGuid(); Console.WriteLine("Asking for random asset " + guid.ToString()); server.GetAsset(guid.ToString()); } if (cmd.Length > 11 && cmd.Substring(0, 11) == "randomforce") { string begUUID = cmd.Substring(12); Guid guid = Guid.NewGuid(); string newGuid = guid.ToString(); newGuid = begUUID + newGuid.Substring(3); Console.WriteLine("Asking for semirandom asset " + newGuid); server.GetAsset(newGuid); } if (cmd.Length > 10 && cmd.Substring(0, 10) == "srandomput") { string begUUID = cmd.Substring(11); Guid guid = Guid.NewGuid(); string newGuid = guid.ToString(); newGuid = begUUID + newGuid.Substring(3); Console.WriteLine("Putting semirandom asset " + newGuid); Asset asset = new Asset(newGuid, 1, false, false, 0, "Random Asset", "Radom Asset Desc", TestUtil.RandomBytes()); server.PutAsset(asset); } if (cmd.Length > 6 && cmd.Substring(0, 6) == "getone") { string uuid = cmd.Substring(7); Console.WriteLine("Asking for named asset " + uuid); Asset asset = server.GetAsset(uuid); using (System.IO.FileStream outstream = System.IO.File.OpenWrite("asset.txt")) { outstream.Write(asset.Data, 0, asset.Data.Length); outstream.Close(); } } if (cmd == "put") { Console.WriteLine("Putting 1000 random assets to server"); Console.WriteLine(DateTime.Now); for (int i = 0; i < 1000; i++) { Asset asset = new Asset(OpenMetaverse.UUID.Random().ToString(), 1, false, false, 0, "Random Asset", "Radom Asset Desc", TestUtil.RandomBytes()); server.PutAsset(asset); } Console.WriteLine("Done: " + DateTime.Now); } if (cmd == "putone") { string uuid = OpenMetaverse.UUID.Random().ToString(); _lastRandom = uuid; Console.WriteLine("Putting 1 random asset to server"); Console.WriteLine(uuid); Console.WriteLine(DateTime.Now); Asset asset = new Asset(uuid, 1, false, false, 0, "Random Asset", "Radom Asset Desc", TestUtil.RandomBytes()); server.PutAsset(asset); Console.WriteLine("Done: " + DateTime.Now); } if (cmd == "repeatput") { Console.WriteLine("Reputting random asset to server"); Console.WriteLine(_lastRandom); Console.WriteLine(DateTime.Now); Asset asset = new Asset(_lastRandom, 1, false, false, 0, "Random Asset", "Radom Asset Desc", TestUtil.RandomBytes()); server.PutAsset(asset); Console.WriteLine("Done: " + DateTime.Now); } if (cmd == "verify") { Dictionary <string, byte[]> uuids = new Dictionary <string, byte[]>(); Console.WriteLine("Putting 1000 random 100K assets to server"); Console.WriteLine(DateTime.Now); SHA1 sha = new SHA1CryptoServiceProvider(); for (int i = 0; i < 1000; i++) { string uuidstr = OpenMetaverse.UUID.Random().ToString(); byte[] randomBytes = TestUtil.RandomBytes(); byte[] challengeHash = sha.ComputeHash(randomBytes); uuids.Add(uuidstr, challengeHash); Asset asset = new Asset(uuidstr, 1, false, false, 0, "Random Asset", "Radom Asset Desc", randomBytes); server.PutAsset(asset); } Console.WriteLine("Done: " + DateTime.Now); Console.WriteLine("Rereading written assets"); Console.WriteLine(DateTime.Now); foreach (KeyValuePair <string, byte[]> kvp in uuids) { Asset a = server.GetAsset(kvp.Key); byte[] hash = sha.ComputeHash(a.Data); if (!TestUtil.Test.test(hash, kvp.Value)) { Console.WriteLine("Mismatched hash on " + kvp.Key); Console.WriteLine("Got " + Util.HashToHex(hash) + " expected " + Util.HashToHex(kvp.Value)); ASCIIEncoding encoding = new ASCIIEncoding(); Console.WriteLine("Data " + encoding.GetString(a.Data)); } } Console.WriteLine("finished verifing assets"); Console.WriteLine(DateTime.Now); } if (cmd == "purgelocals") { server.MaintPurgeLocals(); } if (cmd == "thread") { Console.WriteLine("Starting heavy thread test"); ThreadTest test = new ThreadTest(server, false); test.Start(); } if (cmd == "thread_purgelocal") { Console.WriteLine("Starting heavy thread test"); ThreadTest test = new ThreadTest(server, true); test.Start(); } if (cmd == "threadmesh") { RemoteServer server2 = ConnectServerByConsole(); Console.WriteLine("Starting heavy thread mesh test"); CrossServerThreadTest test = new CrossServerThreadTest(server, server2); test.Start(); } if (cmd == "threadmesh3") { RemoteServer server2 = ConnectServerByConsole(); RemoteServer server3 = ConnectServerByConsole(); Console.WriteLine("Starting heavy thread mesh test"); CrossServerThreadTest3 test = new CrossServerThreadTest3(server, server2, server3); test.Start(); } if (cmd == "testmulticonn") { RemoteServer[] server1 = ConnectServerByConsoleX(10); RemoteServer[] server2 = ConnectServerByConsoleX(10); RemoteServer[] server3 = ConnectServerByConsoleX(10); List <RemoteServer> allServers = new List <RemoteServer>(); allServers.AddRange(server1); allServers.AddRange(server2); allServers.AddRange(server3); CrossServerTestMulticonn test = new CrossServerTestMulticonn(server1[0], server2[0], server3[0], allServers.ToArray(), true); test.Start(); } if (cmd == "testmulticonnsingle") { RemoteServer[] server1 = ConnectServerByConsoleX(10); CrossServerTestMulticonn test = new CrossServerTestMulticonn(server1[0], server1[0], server1[0], server1, false); test.Start(); } if (cmd == "meshbias3") { RemoteServer[] servers2 = ConnectServerByConsoleX(10); RemoteServer server3 = ConnectServerByConsole(); Console.WriteLine("Starting heavy thread biased mesh test"); CrossServerBiasTest3 test = new CrossServerBiasTest3(server, servers2, server3); test.Start(); } if (cmd == "connect") { //fast connect and disconnect to try and kill the whip service for (int i = 0; i < 1000; i++) { server.Stop(); server.Start(); } } if (cmd == "status") { Console.WriteLine(server.GetServerStatus()); } if (cmd == "prefix") { Console.WriteLine(server.GetAssetIds("00000000000000000000000000000000")); } if (cmd == "compare") { RemoteServer server1 = ConnectServerByConsole(); RemoteServer server2 = ConnectServerByConsole(); RunCompare(server1, server2); } if (cmd == "import") { Console.Write("Connection String: "); string connString = Console.ReadLine(); Console.WriteLine(); Console.Write("Start at: "); int startAt = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); _import = new AssetImport(server, connString, startAt); _import.Start(); } if (cmd == "msimport") { Console.Write("Connection String: "); string connString = Console.ReadLine(); Console.WriteLine(); Console.Write("Start at: "); Guid startAt = new Guid(Console.ReadLine()); Console.WriteLine(); _msimport = new MsSqlAssetImport(server, connString, startAt); _msimport.Start(); } if (cmd == "stop import") { if (_import != null) { _import.Stop(); } _import = null; if (_msimport != null) { _msimport.Stop(); } _msimport = null; } }
private string HandleClientComm() { Debug.Log("HandleClientComm"); fullmessage = ""; int bytesRead = 0; byte[] message = new byte[4096]; try { //blocks until a client sends a message Debug.Log("blocked"); bytesRead = clientStream.Read(message, 0, 4096); }catch{ //a socket error has occurred Debug.Log("socketerror"); } if(bytesRead == 0){ Debug.Log("bytesRead = 0"); } //message has successfully been recieved ASCIIEncoding encoder = new ASCIIEncoding(); //System.Console.WriteLine(encoder.GetString(message, 0, bytesRead)); fullmessage = encoder.GetString(message, 0, bytesRead); return fullmessage; }
private void Read() { byte[] buffer = null; ASCIIEncoding encoder = new ASCIIEncoding(); while (true) { int bytesRead = 0; try { buffer = new byte[BUFFER_SIZE]; bytesRead = m_clientse.stream.Read(buffer, 0, BUFFER_SIZE); } catch { //read error has occurred break; } //client has disconnected if (bytesRead == 0) { break; } int ReadLength = 0; for (int i = 0; i < BUFFER_SIZE; i++) { if (buffer[i].ToString("x2") != "cc") { ReadLength++; } else { break; } } if (ReadLength > 0) { byte[] Rc = new byte[ReadLength]; Buffer.BlockCopy(buffer, 0, Rc, 0, ReadLength); string sReadValue = encoder.GetString(Rc, 0, ReadLength); string[] codeInfo = sReadValue.Split('-'); if (codeInfo.Length == 2) { string sSize = codeInfo[0]; string sCode = codeInfo[1]; string sFinalValue = sCode; int nSize = Int32.Parse(sSize); if (sCode.Length >= nSize) { sFinalValue = sCode.Substring(0, nSize); } m_ReceivedValues.Add(sFinalValue); Console.WriteLine($"C# App: Received value : {sFinalValue}"); buffer.Initialize(); } else { Console.WriteLine("C# App: Received value in named pipe is badly formatted (we expect 'size-code')"); } } } m_clientse.stream.Close(); m_clientse.handle.Close(); }
private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { //a socket error has occured break; } if (bytesRead == 0) { //the client has disconnected from the server connectedClients--; //lblNumberOfConnections.Text = connectedClients.ToString(); break; } //message has successfully been received ASCIIEncoding encoder = new ASCIIEncoding(); // Convert the Bytes received to a string and display it on the Server Screen string msg = encoder.GetString(message, 0, bytesRead); //WriteMessage(msg); // Now Echo the message back msg = msg + "Naobek"; Echo(msg, encoder, clientStream); } //tcpClient.Close(); }
////////////////////////// //Function to decrypt data public string DecryptData(String strKey, String strData) { string strResult; //1. Generate the Key used for decrypting if (!InitKey(strKey)) { strResult = "Error. Fail to generate key for decryption"; return(strResult); } //2. Initialize the service provider int nReturn = 0; DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV); //3. Prepare the streams: // mOut is the output stream. // cs is the transformation stream. MemoryStream mOut = new MemoryStream(); CryptoStream cs = new CryptoStream(mOut, desDecrypt, CryptoStreamMode.Write); //4. Remember to revert the base64 encoding into a byte array to restore the original encrypted data stream byte[] bPlain = new byte[strData.Length]; try { bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length); } catch (Exception) { strResult = "Error. Input Data is not base64 encoded."; return(strResult); } long lRead = 0; long lTotal = strData.Length; try { //5. Perform the actual decryption while (lTotal >= lRead) { cs.Write(bPlain, 0, (int)bPlain.Length); //descsp.BlockSize=64 lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize)); } ; ASCIIEncoding aEnc = new ASCIIEncoding(); strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length); //6. Trim the string to return only the meaningful data // Remember that in the encrypt function, the first 5 character holds the length of the actual data // This is the simplest way to remember to original length of the data, without resorting to complicated computations. String strLen = strResult.Substring(0, 5); int nLen = Convert.ToInt32(strLen); strResult = strResult.Substring(5, nLen); nReturn = (int)mOut.Length; return(strResult); } catch (Exception) { strResult = "Error. Decryption Failed. Possibly due to incorrect Key or corrputed data"; return(strResult); } }
public void ParseResult(ref SensorAcqResult rawData) { byte[] data = rawData.Response; rawData.ErrorCode = IsValid(data); if ((int)Errors.SUCCESS != rawData.ErrorCode) { return; } Encoding enc = new ASCIIEncoding(); var recbytes = enc.GetString(data); var module = recbytes.Substring(1, 2); if (int.Parse(module) != rawData.Sensor.ModuleNo) { rawData.ErrorCode = (int)Errors.ERR_INVALID_MODULE; return; } try { var pdata = recbytes.Substring(3, recbytes.Length - 6); var pressure = Convert.ToSingle(pdata); string jsonResultData = string.Format("{0}\"sensorId\":{1},\"data\":\"压强:{2} kPa\"{3}", '{', rawData.Sensor.SensorID, pressure, '}'); double physicalQuantity = 0; switch (rawData.Sensor.FormulaID) { case 8: var pressCul = pressure - rawData.Sensor.Parameters[1].Value; if (ValueHelper.IsEqualZero(rawData.Sensor.Parameters[0].Value)) { rawData.Sensor.Parameters[0].Value = 1; } var settlement = 1000 * pressCul / (rawData.Sensor.Parameters[0].Value * 9.8f); physicalQuantity = settlement; break; case 10: jsonResultData = string.Format("{0}\"sensorId\":{1},\"data\":\"米水柱:{2} mH2O\"{3}", '{', rawData.Sensor.SensorID, pressure, '}'); int type = (int)rawData.Sensor.Parameters[0].Value; double waterLevel = pressure * 100; double len = rawData.Sensor.Parameters[1].Value; // 底长 switch (type) { case 0: //三角堰 physicalQuantity = (float)(Math.Pow(waterLevel, 2.5) * (0.0142 - ((int)(waterLevel / 5)) * 0.0001)); break; case 1: //矩形堰 physicalQuantity = (float)(Math.Pow(waterLevel, 1.5) * len * 0.0186); break; case 2: // 梯形堰 physicalQuantity = (float)(Math.Pow(waterLevel, 1.5) * (len - 0.2 * waterLevel) * 0.01838); break; } break; } var raws = new double[] { pressure }; var phys = new double[] { physicalQuantity }; rawData.Data = new SensorData(raws, phys, raws) { JsonResultData = jsonResultData }; //rawData.Data = new PressureData(pressure, physicalQuantity) //{ // JsonResultData = jsonResultData //}; } catch (Exception ex) { rawData.ErrorCode = (int)Errors.ERR_DATA_PARSEFAILED; _logger.ErrorFormat("mpm pressure [id:{0},m:{1}] parsedfailed ,received bytes{3},ERROR : {2}", rawData.Sensor.SensorID, rawData.Sensor.ModuleNo, ex.Message, ValueHelper.BytesToHexStr(rawData.Response)); } }
public string ReadString(int length) { var buffer = ReadBytes(length); return(Unescape(_encoder.GetString(buffer))); }
/// <summary> /// Invoked when the register button is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void registerButton_Click(object sender, EventArgs e) { string email = emailTextBox.Text; string displayName = displaynameTextBox.Text; string username = usernameTextBox.Text; string password = passwordTextBox.Text; string confirmPassword = confirmPasswordTextBox.Text; if (email == null || !email.Contains("@")) { MessageBox.Show("A valid email must be entered.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (username == null || username.Length < 6) { MessageBox.Show("A valid username must be entered.", "Invalid Username", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (password.ToLower() != confirmPassword.ToLower()) { MessageBox.Show("Your passwords do not match.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (password.Length < 6) { MessageBox.Show("A valid password must be entered.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { ProgressWindow progressWindow = new ProgressWindow("Registering", "Contacting server"); progressWindow.Marquee = true; progressWindow.Show(); this.Enabled = false; FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionregister&email=" + System.Web.HttpUtility.UrlEncode(email) + "&username="******"&password="******"" ? ("&displayname=" + System.Web.HttpUtility.UrlEncode(displayName)) : "")); downloader.Start(); while (downloader.Complete == false) { if (downloader.Error != "") { MessageBox.Show("An error occured while connecting to the server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Application.DoEvents(); } this.Enabled = true; progressWindow.Dispose(); ASCIIEncoding encoding = new ASCIIEncoding(); string response = encoding.GetString(downloader.FileData); if (response.ToLower() == "usernameinuse") { MessageBox.Show("An account already exists with the username that your provided.", "Invalid Register", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (response.ToLower() == "emailinuse") { MessageBox.Show("An account already exists with the email that your provided.", "Invalid Register", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (response.ToLower() == "valid") { MessageBox.Show("Your account has successfully been registered with the server and you have been logged in. We hope you like being a member of Binary Phoenix's community.", "Registration Successfull", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); Fusion.GlobalInstance.CurrentUsername = username; Fusion.GlobalInstance.CurrentPassword = password; return; } else { MessageBox.Show("Unexpected value returned from server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/* Get string from dbt. */ public static string strFromDBT(DatabaseEntry dbt) { System.Text.ASCIIEncoding decode = new ASCIIEncoding(); return(decode.GetString(dbt.Data)); }
void Update() { if (tcpClient == null || serverStream == null || !serverStream.DataAvailable) return; // Assumption: max message size is 1024 characters byte [] msg = new byte[1024]; int bytesRead = serverStream.Read(msg, 0, 1024); ASCIIEncoding encoder = new ASCIIEncoding(); string message = encoder.GetString(msg, 0, bytesRead); foreach (GameObject go in onReceivedMessageListeners) { go.SendMessage("OnReceiveMessage", message); } }
public virtual String ReadString(int length) { Byte[] buffer = ReadBytes(length); return(asciiEncoding.GetString(buffer, 0, length)); }
/// <summary> /// Converts byte array to string /// </summary> /// <param name="byteArr">Byte array to be converted</param> /// <returns>Converted string</returns> public static string ByteArrayToString(byte[] byteArr) { ASCIIEncoding encoding = new ASCIIEncoding(); return(encoding.GetString(byteArr)); }
public void PgmClient(ParametresThread param) { TcpListener serv = new TcpListener(IPAddress.Parse(LocalIP), 11000); byte[] data = new byte[1464]; data = (byte[])aResult.AsyncState; //Décryptage et affichage du message. ASCIIEncoding eEncoding = new ASCIIEncoding(); string message = eEncoding.GetString(data); string m = message.Substring(0, 2); switch (m) { case "#c": { message = message.Substring(2, message.Length - 3); string pseudo = message.Split(' ')[0]; string mdp = message.Split(' ')[1]; ConnexionBase.Open(); OleDbCommand Commande = new OleDbCommand(); Commande.Connection = ConnexionBase; Commande.CommandText = "SELECT * FROM Utilisateurs WHERE Pseudo <> @PSEUDO AND MotDePasse <> @MOTDEPASSE"; Commande.Parameters.Add("PSEUDO", pseudo); Commande.Parameters.Add("MOTDEPASSE", mdp); Commande.ExecuteNonQuery(); OleDbDataReader reader = Commande.ExecuteReader(); break; } case "#d": { message = message.Substring(2, message.Length - 3); string pseudo = message.Split(' ')[0]; string mdp = message.Split(' ')[1]; ConnexionBase.Open(); OleDbCommand Commande = new OleDbCommand(); Commande.Connection = ConnexionBase; Commande.CommandText = "DELETE FROM Utilisateurs WHERE Pseudo <> @PSEUDO AND MotDePasse <> @MOTDEPASSE"; Commande.Parameters.Add("PSEUDO", pseudo); Commande.Parameters.Add("MOTDEPASSE", mdp); Commande.ExecuteNonQuery(); OleDbDataReader reader = Commande.ExecuteReader(); break; } case "#m": { message = message.Substring(2, message.Length - 3); Discussion.Items.Add(message); break; } } }
protected void Page_Load(object sender, EventArgs e) { String userName = Environment.UserName; //Afawzi Response.Write(userName); #region Test SAML XML Reading //String test = "<Response xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:ds='http://www.w3.org/2000/09/xmldsig#' xmlns:saml='urn:oasis:names:tc:SAML:2.0:assertion' ID='_0d3d6141-94cf-4954-9a10-ca0caddc53b2' Version='2.0' IssueInstant='2018-08-06T15:27:38.7931151+03:00' Destination='http://localhost:52120/login.aspx' xmlns='urn:oasis:names:tc:SAML:2.0:protocol'><saml:Issuer>Idp_Mohammed_Tahtamouni</saml:Issuer><Status><StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success' /></Status><saml:Assertion Version='2.0' ID='_5bb27f4b-f190-4bbc-9ae4-c4545fec353b' IssueInstant='2018-08-06T15:27:38.7941152+03:00'><saml:Issuer>Idp_Mohammed_Tahtamouni</saml:Issuer><Signature xmlns='http://www.w3.org/2000/09/xmldsig#'><SignedInfo><CanonicalizationMethod Algorithm='http://www.w3.org/2001/10/xml-exc-c14n#' /><SignatureMethod Algorithm='http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' /><Reference URI='#_5bb27f4b-f190-4bbc-9ae4-c4545fec353b'><Transforms><Transform Algorithm='http://www.w3.org/2000/09/xmldsig#enveloped-signature' /><Transform Algorithm='http://www.w3.org/2001/10/xml-exc-c14n#' /></Transforms><DigestMethod Algorithm='http://www.w3.org/2001/04/xmlenc#sha256' /><DigestValue>e5DxYO6UKAbt21WDryNmvYdFbxd7HmXUryOnsKlFUso=</DigestValue></Reference></SignedInfo><SignatureValue>SVUqe9QFeVwtpgYvm9OMoAevS2n+pgCNtKD1mjGhyFawWc3kGrvAVAorbuKJwnr/fS0zSxeUkE8F/DrxVTd8xWJOjFn8KriqdFlMqpLxnLbEAabuIBjUf+Rss6RKOazlpm5jCzhrhr4k7hGZExL+bAWYzbt7ff+GrHAcP4dt2z8=</SignatureValue><KeyInfo><KeyValue><RSAKeyValue><Modulus>qfLbknPGfeOeZos/SbqGhR9CIPFt+0VURDZPi6iODvyDlFI3mHULCs0oLj/lA21bnjF6+9onFJ7kfpYms1djE4iEWOG3FbghtyurfGDpbtkQiI0jWadVfwnK69lyz8SsrFiZlQ5thcmaIKJTPw+J/zQANSZ0Rn3Ktb4i2ah6u+8=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue></KeyInfo></Signature><saml:Subject><saml:NameID Format='urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified'>Authentication</saml:NameID><saml:SubjectConfirmation Method='urn:oasis:names:tc:SAML:2.0:cm:bearer'><saml:SubjectConfirmationData Recipient='http://localhost:52120/login.aspx' NotOnOrAfter='2018-08-06T15:32:38.7941152+03:00' /></saml:SubjectConfirmation></saml:Subject><saml:Conditions NotBefore='2018-08-06T15:27:38.7941152+03:00' NotOnOrAfter='2018-08-06T15:32:38.7941152+03:00'><saml:AudienceRestriction><saml:Audience>http://localhost:52120/login.aspx</saml:Audience></saml:AudienceRestriction></saml:Conditions><saml:AuthnStatement AuthnInstant='2018-08-06T15:27:38.7941152+03:00' SessionIndex='_5bb27f4b-f190-4bbc-9ae4-c4545fec353b'><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement><saml:AttributeStatement /></saml:Assertion></Response>"; //XmlDocument doc = new XmlDocument(); //doc.PreserveWhitespace = true; //doc.XmlResolver = null; //doc.LoadXml(test); //XmlNodeList xmlIssuer = doc.GetElementsByTagName("saml:Issuer"); //XmlNodeList xmlResponse = doc.GetElementsByTagName("Response"); //XmlNodeList xmlStatus = doc.GetElementsByTagName("StatusCode"); //XmlNodeList xmlAssertion = doc.GetElementsByTagName("saml:Assertion"); //XmlNodeList xmlSamlConditions = doc.GetElementsByTagName("saml:Conditions"); //for (int i = 0; i < xmlResponse.Count; i++) //{ // String ResponseID = xmlResponse[i].Attributes["ID"].Value; // EX. _0d3d6141-94cf-4954-9a10-ca0caddc53b2 //} //for (int i = 0; i <= xmlIssuer.Count - 1; i++) //{ // String IDP = xmlIssuer[i].ChildNodes.Item(0).InnerText.Trim(); // Idp_Mohammed_Tahtamouni //} //for (int i = 0; i <= xmlStatus.Count - 1; i++) //{ // String Status = xmlStatus[i].Attributes[0].Value.ToString(); // urn:oasis:names:tc:SAML:2.0:status:Success //} //for (int i = 0; i < xmlAssertion.Count; i++) //{ // String AssertionID = xmlAssertion[i].Attributes["ID"].Value; // EX. _5bb27f4b-f190-4bbc-9ae4-c4545fec353b //} //for (int i = 0; i < xmlSamlConditions.Count; i++) //{ // String SamlStartDateTime = xmlSamlConditions[i].Attributes["NotBefore"].Value; // EX. 2018-08-06T15:27:38.7941152+03:00 // String SamlEndDateTime = xmlSamlConditions[i].Attributes["NotOnOrAfter"].Value; // EX. 2018-08-06T15:32:38.7941152+03:00 // DateTime SamlStartDate = Convert.ToDateTime(SamlStartDateTime); // DateTime SamlEndDate = Convert.ToDateTime(SamlEndDateTime); // DateTime currentDateTime = DateTime.Now; // int sessionValid = DateTime.Compare(SamlEndDate, currentDateTime); // Not 1: means ==> NOT Valid // } #endregion Test SAML XML Reading #region Test Domain Settings // String userNameWithDomain = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //LOGISTICS\AFawzi //String userName = "******"; // Environment.UserName; Afawzi // String Password = "******"; // String userName = Environment.UserName; //Afawzi // String Password = "******"; // PrincipalContext principalContext = //new PrincipalContext(ContextType.Domain, "10.10.65.11"); // KGACHQ 10.10.65.11 logistics.intra 10.200.65.55 // bool userValid = principalContext.ValidateCredentials(userName, Password); #endregion Test Domain Settings if (!IsPostBack) { //jkb #region Test Response Values //string[] keys = Request.Form.AllKeys; //for (int i = 0; i < keys.Length; i++) //{ // Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>"); //} #endregion Test Response Values #region Variables String SAMLAssertion = String.Empty; String SAML = String.Empty; String ResponseID = String.Empty; String IDP = String.Empty; String Status = String.Empty; String AssertionID = String.Empty; String SamlStartDateTime = String.Empty; String SamlEndDateTime = String.Empty; int AssertionValid = -1; XmlDocument xmlDoc; #endregion Variables if (Session["sessionValid"] != null) { String IsValid = Session["sessionValid"].ToString(); if (IsValid == "1") { Response.Redirect("authenticatedPage.aspx"); } } else { #region Read SAML Response if (Request.Form["SAMLAssertion"] != null) { SAMLAssertion = Request.Form["SAMLAssertion"].ToString(); ASCIIEncoding enc = new ASCIIEncoding(); SAML = enc.GetString(Convert.FromBase64String(SAMLAssertion)); xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.XmlResolver = null; xmlDoc.LoadXml(SAML); XmlNodeList xmlIssuer = xmlDoc.GetElementsByTagName("saml:Issuer"); XmlNodeList xmlResponse = xmlDoc.GetElementsByTagName("Response"); XmlNodeList xmlStatus = xmlDoc.GetElementsByTagName("StatusCode"); XmlNodeList xmlAssertion = xmlDoc.GetElementsByTagName("saml:Assertion"); XmlNodeList xmlSamlConditions = xmlDoc.GetElementsByTagName("saml:Conditions"); for (int i = 0; i < xmlResponse.Count; i++) { ResponseID = xmlResponse[i].Attributes["ID"].Value; // EX. _0d3d6141-94cf-4954-9a10-ca0caddc53b2 } for (int i = 0; i <= xmlIssuer.Count - 1; i++) { IDP = xmlIssuer[i].ChildNodes.Item(0).InnerText.Trim(); // Idp_Mohammed_Tahtamouni } for (int i = 0; i <= xmlStatus.Count - 1; i++) { Status = xmlStatus[i].Attributes[0].Value.ToString(); // urn:oasis:names:tc:SAML:2.0:status:Success } for (int i = 0; i < xmlAssertion.Count; i++) { AssertionID = xmlAssertion[i].Attributes["ID"].Value; // EX. _5bb27f4b-f190-4bbc-9ae4-c4545fec353b } for (int i = 0; i < xmlSamlConditions.Count; i++) { SamlStartDateTime = xmlSamlConditions[i].Attributes["NotBefore"].Value; // EX. 2018-08-06T15:27:38.7941152+03:00 SamlEndDateTime = xmlSamlConditions[i].Attributes["NotOnOrAfter"].Value; // EX. 2018-08-06T15:32:38.7941152+03:00 DateTime SamlStartDate = Convert.ToDateTime(SamlStartDateTime); DateTime SamlEndDate = Convert.ToDateTime(SamlEndDateTime); DateTime currentDateTime = DateTime.Now; AssertionValid = DateTime.Compare(SamlEndDate, currentDateTime); // Not 1: means ==> NOT Valid Session["sessionValid"] = AssertionValid; Session["AssertionID"] = AssertionID; Session["ResponseID"] = ResponseID; if (AssertionValid == 1) { Response.Redirect("authenticatedPage.aspx"); } } } #endregion Read SAML Response } } }
/// <summary> /// Unity3D server thread, talk to Unity3D to respond requests /// </summary> /// <returns></returns> private void TalkToUnity() { bool connected = false; while (!stopAll) { if (!connected) { //Can hold 4 client requests in the queue socListener.Listen(4); socWorker = socListener.Accept(); connected = true; Console.WriteLine("\n^_^ < Unity3D > --- Connection Erected"); } else { try { socWorker.Receive(recBuffer); //Get request message recStr = encoder.GetString(recBuffer); //Convert to string int index = recStr.IndexOf('\n'); //Parse string: remove '\n' recStr = recStr.Remove(index); String[] tokens = recStr.Split(new char[] { '?' }); int which = 0; if (tokens[0] != "Ready" && tokens[0] != "Bye" && tokens[0] != "PutOpenvibeButton") { which = System.Convert.ToInt32(tokens[1]); } switch (tokens[0]) { case "Ready": //Ready confirm sendStr = "Ready!\n"; break; case "GetOpenvibeAnalog": if (which <= getOpenvibeAnalogsAlive) { // Encode the data in a message getOpenvibeAnalog[which - 1].Update(); sendStr = getOpenvibeAnalog[which - 1].Encode(); } else { sendStr = "ERROR: GetOpenvibeAnalog # " + which.ToString() + " is not turned on\n"; } break; case "GetOpenvibeButton": if (which <= getOpenvibeButtonsAlive) { // Encode the data in a message getOpenvibeButton[which - 1].Update(); sendStr = getOpenvibeButton[which - 1].Encode(); } else { sendStr = "ERROR: GetOpenvibeButton # " + which.ToString() + " is not turned on\n"; } break; case "PutOpenvibeButton": int buttNum = System.Convert.ToInt32(tokens[1]); // Get a button's number from UIVA_Client Console.WriteLine("UIVA_UnityToOpenvibeButton : Button[" + tokens[1] + "] is marked."); putOpenvibeButton[0].Mark(buttNum); sendStr = ""; break; case "Bye": //Disconnect confirm sendStr = "Bye!\n"; connected = false; Console.WriteLine("^_^ < Unity3D > --- Connection Ended"); break; default: sendStr = "ERROR: invalid request, what do you mean <" + recStr + ">\n"; break; } if (tokens[0] != "PutOpenvibeButton") { sendBuffer = encoder.GetBytes(sendStr); //Encode socWorker.Send(sendBuffer); //Send } } catch (Exception e) { Console.WriteLine("*.* < Unity3D > --- Connection Lost"); #if __VERBOSE__ Console.WriteLine(e.ToString()); #endif connected = false; } } } // End of while(!stopAll) loop } // End of thread TalkToUnity()
/// <summary> /// Try to connect to the server specified. /// </summary> /// <param name="Indirizzo">Address of the server to connect.</param> /// <param name="Port">Port of the server to connect.</param> /// <returns>True if the connection is successfull, false otherwise.</returns> /// <exception cref="TCPLibrary.Core.AlreadyConnectedException" /> /// <exception cref="System.Net.Sockets.SocketException" /> public virtual Boolean Connect(String Indirizzo, Int32 Port) { if (!Connected) { IPHostEntry addr = Dns.GetHostEntry(Indirizzo); IPAddress ip = null; foreach (var itm in addr.AddressList) { if (itm.AddressFamily == AddressFamily.InterNetwork) { ip = itm; break; } } if (ip != null) { _address = new IPEndPoint(ip, Port); _socket = new TcpClient(); try { _socket.Connect(_address); } catch (SocketException) { _socket = null; _address = null; throw; } tr = new BinaryReader(_socket.GetStream()); tw = new BinaryWriter(_socket.GetStream()); // Receive the confirmation of the status of the connection to the server. // Is CONNECTEDTCPSERVER if the connection is successfull, all other cases are wrong. Int32 Length = Convert.ToInt32(tr.ReadInt32()); byte[] arr = new byte[Length]; tr.Read(arr, 0, Length); ASCIIEncoding ae = new ASCIIEncoding(); String Accept = ae.GetString(arr, 0, arr.Length); if (Accept == "CONNECTEDTCPSERVER") { _active = true; Thread thd = new Thread(new ThreadStart(MainThread)); thd.IsBackground = true; thd.Name = "Client connected to " + Indirizzo + ":" + Port.ToString(); thd.Start(); if (OnConnected != null) { OnConnected(this); } return(true); } else { Stop(); if (OnConnectFailed != null) { OnConnectFailed(this, arr); } return(false); } } else { return(false); } } else { throw new ArgumentException("The client is already connected!"); } }
/*DESCRIPTION -- This function reads messages sent from the server and ouputs it to a gui component * (ARGUMENTS) -- () -> Void * PRECONDITION -- Connection must be established * POSTCONDITION -- Outputs server message to gui component * EXAMPLE (s) -- readMessage() -> Server Said: "THis is my first message"; */ private void readMessage() { Byte[] read = new Byte[32]; // creating byte array to store bytes coming from server clientStream.Read(read, 0, read.Length); if (read != null) { ouput_txtBox.Invoke(new Action(() => ouput_txtBox.AppendText("\nServer Says" + encoder.GetString(read)))); } }
public int Write <T>(List <PointGroup <T> > pointGroupList) { try { if (_isConnect) { ASCIIEncoding encoding = new ASCIIEncoding(); var sendBytes = creatWriteData(pointGroupList); var receiveBuffer = new byte[12768]; _log.ByteSteamLog(ActionType.SEND, sendBytes); if (_socket.Send(sendBytes) != -1) { Thread.Sleep(10); int count = _socket.Receive(receiveBuffer); var receivedata = new byte[count]; Array.Copy(receiveBuffer, receivedata, count); _log.ByteSteamLog(ActionType.RECEIVE, receiveBuffer); var receiveStr = encoding.GetString(receivedata); receiveStr = receiveStr.Replace("<", ""); var strArrary = receiveStr.Split(new char[] { '>' }, StringSplitOptions.RemoveEmptyEntries); if (strArrary.Length > 2) { if (strArrary[1] == "12") { return(1); } else if (strArrary[1] == "22") { string errorInfo = ""; for (int i = 2; i < strArrary.Length - 1; i++) { errorInfo = string.Concat(errorInfo, "<", strArrary[i], ">"); } Log.ErrorLog(string.Format("Freedom Write {0} ", errorInfo)); return(-1); } else { Log.ErrorLog(string.Format("Freedom Write {0} ", "receive function code error!")); return(-1); } } else { Log.ErrorLog(string.Format("Freedom Write {0} ", "receive data length too less!")); return(-1); } } else { Log.ErrorLog(string.Format("Freedom Write {0} ", "send buffer fail!")); return(-1); } } else { Log.ErrorLog(string.Format("Freedom Write {0} ", "connect is not build!")); return(-1); } } catch (Exception e) { DisConnect(); Log.ErrorLog(string.Format("Freedom Write {0} ", e.Message)); return(-1); } }
public void HandleClientComm() { NetworkStream clientStream = client.GetStream(); //*#*byte[] message = new byte[1030]; byte[] message = new byte[1024]; int bytesRead; while (true) { bytesRead = 0; try { //blocks until a server sends a message //BLOCKING READ bytesRead = clientStream.Read(message, 0, message.Length); //print((float)bytesRead / 1000); } catch (Exception e) { //socket error has occured //print("ERROR : " + e.Message + " " + e.Data + " " + e.StackTrace); print(e.GetBaseException()); break; } if (bytesRead == 0) { //Client is disconnected from server //print("ERROR : READ = 0"); break; } ASCIIEncoding encoder = new ASCIIEncoding(); string read_str = encoder.GetString(message, 0, bytesRead); read_object ro = new read_object(read_str, bytesRead.ToString()); statics.read_object_list.Add(ro); } client_control.connected = 0; client.Close(); client = null; //ADD server message to static buffer read_object ro2 = new read_object("Disconnected...", "0"); statics.read_object_list.Add(ro2); }
/// <summary>Extracts the tar data into a specified directory.</summary> /// <param name="bytes">The tar data to extract.</param> /// <param name="directory">The directory to extract the content to.</param> /// <param name="prefix">The directory prefix that is trimmed off all the paths encountered in this archive, or a null reference.</param> internal static void Unpack(byte[] bytes, string directory, string prefix) { ASCIIEncoding ascii = new ASCIIEncoding(); UTF8Encoding utf8 = new UTF8Encoding(); int position = 0; string longLink = null; while (position < bytes.Length) { string name; if (longLink != null) { name = longLink; longLink = null; } else { name = utf8.GetString(bytes, position, 100).TrimEnd('\0'); } if (name.Length == 0) { /* * The name is empty. This marks the end of the file. * */ break; } else { /* * Read the header and advance the position. * */ string sizeString = ascii.GetString(bytes, position + 124, 12).Trim('\0', ' '); int size = Convert.ToInt32(sizeString, 8); int mode; mode = name[name.Length - 1] == '/' ? 53 : (int)bytes[position + 156]; if (bytes[position + 257] == 0x75 && bytes[position + 258] == 0x73 && bytes[position + 259] == 0x74 && bytes[position + 260] == 0x61 && bytes[position + 261] == 0x72 && bytes[position + 262] == 0x00) { /* * This is a POSIX ustar archive. * */ string namePrefix = utf8.GetString(bytes, position + 345, 155).TrimEnd(' '); if (namePrefix.Length != 0) { if (namePrefix[namePrefix.Length - 1] != '/' && name[0] != '/') { name = namePrefix + '/' + name; } else { name = namePrefix + name; } } } else if (bytes[position + 257] == 0x75 && bytes[position + 258] == 0x73 && bytes[position + 259] == 0x74 && bytes[position + 260] == 0x61 && bytes[position + 261] == 0x72 && bytes[position + 262] == 0x20) { /* * This is a GNU tar archive. * TODO: Implement support for GNU tar archives here. * */ } position += 512; /* * Process the data depending on the mode. * */ if (mode == 53) { /* * This is a directory. * */ if (name[name.Length - 1] == '/') { name = name.Substring(0, name.Length - 1); } name = name.Replace('/', Path.DirectorySeparatorChar); if (prefix != null) { if (name.StartsWith(prefix + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) { name = name.Substring(prefix.Length + 1); } else if (string.Equals(name, prefix, StringComparison.OrdinalIgnoreCase)) { name = string.Empty; } } try { Directory.CreateDirectory(Path.Combine(directory, name)); } catch { } } else if (mode < 49 || mode > 54) { /* * This is a normal file. * */ if (name != "././@LongLink") { name = name.Replace('/', Path.DirectorySeparatorChar); if (prefix != null && name.StartsWith(prefix + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) { name = name.Substring(prefix.Length + 1); } } int blocks = size + 511 >> 9; byte[] buffer = new byte[size]; Array.Copy(bytes, position, buffer, 0, size); position += blocks << 9; if (name == "././@LongLink") { longLink = utf8.GetString(buffer); if (longLink.Length != 0 && longLink[longLink.Length - 1] == '\0') { longLink = longLink.Substring(0, longLink.Length - 1); } } else { string file = Path.Combine(directory, name); try { Directory.CreateDirectory(Path.GetDirectoryName(file)); } catch { } if (File.Exists(file)) { try { File.SetAttributes(file, FileAttributes.Normal); } catch { } } File.WriteAllBytes(Path.Combine(directory, name), buffer); } } else { /* * Unsupported mode. * */ } } } }
public Client(int port, string IP) { TcpClient client = new TcpClient(); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(IP), port); client.Connect(serverEndPoint); NetworkStream clientStream = client.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = new byte[4096]; int bytesRead, bytesRead2, fileSizeI, bytesRead3, bytesRead4; buffer = encoder.GetBytes("HELLO"); byte[] message = new byte[4096]; byte[] fileSizeB = new byte[4096]; byte[] fileNameB = new byte[4096]; clientStream.Write(buffer, 0, buffer.Length); while (true) { bytesRead = 0; try { bytesRead = clientStream.Read(message, 0, 4096); } catch { MessageBox.Show("An error has occured when trying to connect to the server... 0x04", "Error: 0x04"); break; } if (bytesRead == 0) { MessageBox.Show("We have disconnected from the server... 0x05", "Error: 0x05"); break; } if (encoder.GetString(message).Replace("\0", "") == "HELLO") { buffer = encoder.GetBytes("GETFILESIZE"); clientStream.Write(buffer, 0, buffer.Length); while (true) { bytesRead2 = 0; try { bytesRead2 = clientStream.Read(fileSizeB, 0, 4096); } catch { MessageBox.Show("An error has occured when trying to receive the file size... 0x07", "Error: 0x07"); break; } if (bytesRead2 == 0) { MessageBox.Show("We have disconnected from the server... 0x08", "Error: 0x08"); break; } fileSizeI = Int32.Parse(encoder.GetString(fileSizeB).Replace("\0", "")); buffer = encoder.GetBytes("GETFILENAME"); clientStream.Write(buffer, 0, buffer.Length); while (true) { bytesRead3 = 0; try { bytesRead3 = clientStream.Read(fileNameB, 0, 4096); } catch { MessageBox.Show("An error has occured when trying to receive the filename... 0x09", "Error: 0x09"); break; } if(bytesRead3 == 0) { MessageBox.Show("We have disconnected from the server... 0x10", "Error: 0x10"); break; } string fileNameS = encoder.GetString(fileNameB).Replace("\0", ""); buffer = encoder.GetBytes("GETFILECONTENTS"); clientStream.Write(buffer, 0, buffer.Length); byte[] file = new byte[fileSizeI]; while (true) { bytesRead4 = 0; try { bytesRead4 = clientStream.Read(file, 0, fileSizeI); } catch { MessageBox.Show("An error has occured when trying to receive the file... 0x11", "Error: 0x11"); break; } if (bytesRead4 == 0) { MessageBox.Show("We have disconnected from the server... 0x12", "Error: 0x12"); break; } try { string path = Environment.GetEnvironmentVariable("USERPROFILE") + "\\Downloads\\YAFTP\\" + fileNameS; FileStream fs = File.Create(path, fileSizeI, FileOptions.None); BinaryWriter bw = new BinaryWriter(fs); bw.Write(file); bw.Close(); fs.Close(); } catch (IOException) { } buffer = encoder.GetBytes("CLOSETHECONNECTION"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Close(); client.Close(); Thread.CurrentThread.Abort(); } } } } else { MessageBox.Show("Unknown command reply received from the server...0x06", "Error: 0x06"); break; } } }
private void ProcessData(byte[] data) // answer received from server { try { int[] parm2 = new int[1]; ASCIIEncoding buffer = new ASCIIEncoding(); string command_type = buffer.GetString(data, 0, data.Length); Debug.Write(command_type + "\n"); string[] vals = command_type.Split(' '); if (vals.Length > 3) { switch (vals[2]) { case "Restore": console.Invoke(new CrossThreadCallback(console.CATCallback), "Restore", 0, parm2, ""); break; case "Freq_up": console.Invoke(new CrossThreadCallback(console.CATCallback), "VFOA step up", 2, parm2, ""); break; case "Freq_down": console.Invoke(new CrossThreadCallback(console.CATCallback), "VFOA step down", 2, parm2, ""); break; case "Step_down": console.Invoke(new CrossThreadCallback(console.CATCallback), "StepSize VFOA down", 1, parm2, ""); break; case "Step_up": console.Invoke(new CrossThreadCallback(console.CATCallback), "StepSize VFOA up", 1, parm2, ""); break; case "Band_up": console.Invoke(new CrossThreadCallback(console.CATCallback), "Band up", 1, parm2, ""); break; case "Band_down": console.Invoke(new CrossThreadCallback(console.CATCallback), "Band down", 1, parm2, ""); break; case "Vol+": console.Invoke(new CrossThreadCallback(console.CATCallback), "AF+", 1, parm2, ""); break; case "Vol-": console.Invoke(new CrossThreadCallback(console.CATCallback), "AF-", 1, parm2, ""); break; case "Mute": console.Invoke(new CrossThreadCallback(console.CATCallback), "AF_mute", 0, parm2, ""); break; case "Power": console.Invoke(new CrossThreadCallback(console.CATCallback), "Power toggle", 1, parm2, ""); break; case "Mem+": console.Invoke(new CrossThreadCallback(console.CATCallback), "Memory up", 0, parm2, ""); break; case "Mem-": console.Invoke(new CrossThreadCallback(console.CATCallback), "Memory down", 0, parm2, ""); break; case "MemRecall": console.Invoke(new CrossThreadCallback(console.CATCallback), "Memory recall", 0, parm2, ""); break; case "MemClear": console.Invoke(new CrossThreadCallback(console.CATCallback), "Mmeory clear", 0, parm2, ""); break; case "MemStore": console.Invoke(new CrossThreadCallback(console.CATCallback), "Memory store", 0, parm2, ""); break; case "Return": console.Invoke(new CrossThreadCallback(console.CATCallback), "Restore VFOA", 0, parm2, ""); break; case "Exit": console.Invoke(new CrossThreadCallback(console.CATCallback), "CLOSE", 0, parm2, ""); break; } } if (debug && !console.ConsoleClosing) { console.Invoke(new DebugCallbackFunction(console.DebugCallback), "WinLIRC command: " + command_type); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
private SmtpResponse Read () { byte [] buffer = new byte [512]; int position = 0; bool lastLine = false; do { CheckCancellation (); int readLength = stream.Read (buffer, position, buffer.Length - position); if (readLength > 0) { int available = position + readLength - 1; if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r')) for (int index = available - 3; ; index--) { if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') { lastLine = buffer [index + 4] == ' '; break; } } // move position position += readLength; // check if buffer is full if (position == buffer.Length) { byte [] newBuffer = new byte [buffer.Length * 2]; Array.Copy (buffer, 0, newBuffer, 0, buffer.Length); buffer = newBuffer; } } else { break; } } while (!lastLine); if (position > 0) { Encoding encoding = new ASCIIEncoding (); string line = encoding.GetString (buffer, 0, position - 1); // parse the line to the lastResponse object SmtpResponse response = SmtpResponse.Parse (line); return response; } else { throw new System.IO.IOException ("Connection closed"); } }
public static string FromASCIIByteArray(byte[] characters) { ASCIIEncoding encoding = new ASCIIEncoding(); return(encoding.GetString(characters)); }