private GetChars ( byte bytes, int byteCount, char chars, int charCount, bool flush ) : int | ||
bytes | byte | |
byteCount | int | |
chars | char | |
charCount | int | |
flush | bool | |
return | int |
private string Recieve(Socket RecieveSocket) { string[] Splitter; string FullREC = ""; byte[] buffer = new byte[RecieveSocket.Available]; int iRx = RecieveSocket.Receive(buffer); char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(buffer, 0, iRx, chars, 0); System.String Recieved = new System.String(chars); FullREC += Recieved; Splitter = FullREC.Split('\a'); while (Splitter[Splitter.Length - 1] != "MSGEND") { buffer = new byte[RecieveSocket.Available]; iRx = RecieveSocket.Receive(buffer); chars = new char[iRx]; charLen = d.GetChars(buffer, 0, iRx, chars, 0); Recieved = new System.String(chars); FullREC += Recieved; Splitter = FullREC.Split('\a'); } return(FullREC); }
public string ReadLine() { bool startLine = true; int rest = 0; if (charPos >= fileSize) { return(null); } char *buffer = stackalloc char[1]; StringBuilder builder = new StringBuilder(); while (charPos < fileSize) { decoder.GetChars(memBytePtr + charPos, charLen, buffer, 1, false); charBuffer = *buffer; switch (charBuffer) { case (char)65279: charBuffer = ' '; break; case '\r': case '\n': if ((charBuffer == '\r') && (this.Peek() == '\n')) { charPos += charLen; } charPos += charLen; rest = 0; return(builder.ToString()); } if (!char.IsWhiteSpace(charBuffer)) { startLine = false; } if (!startLine) { if (charBuffer == ' ') { rest++; } else { if (rest > 0) { builder.Append(' ', rest); rest = 0; } builder.Append(charBuffer); } } charPos += charLen; } return(builder.ToString()); }
/// Client Received data from Server /// </summary> /// <param name="asyn">IAsyncResult</param> public void ClientDataReceived(IAsyncResult asyn) { try { SocketPacket socPacket = (SocketPacket)asyn.AsyncState; int iRx = socPacket.mSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.ASCII.GetDecoder(); int charLen = d.GetChars(socPacket.mDataBuffer, 0, iRx, chars, 0); string data = new System.String(chars); data = data.Trim(); //Logger.TranferDataLog(" Reciep -" + data + "-" + DateTime.Now.ToString()); if (data.Contains("RECEIVE")) { TransferSaleDataToServer.GetScriptAndFlusToDataBase(); } else if (data.Contains("TRANSFER")) // format : TRANSFER -- ra lenh chuyen so lieu { TransferSaleDataToServer.SaveFileAndLog(); } ClientWaitData(); } catch (SocketException ex) { Logger.TranferDataLog("SocketException " + ex.ToString()); ClearConectSocket(); } catch (Exception ex) { isCallRecieptData = true; Logger.TranferDataLog("Error Data ClientDataReceived: " + ex.ToString()); } }
public static Highscore Load(Stream fs, System.Text.Decoder decoder) { const int length = 4; byte[] data = new byte[length]; char[] chars; string name; fs.Read(data, 0, length); var bytesCount = System.BitConverter.ToInt32(data, 0); if (bytesCount > 0 && bytesCount < 100000) { data = new byte[bytesCount]; fs.Read(data, 0, bytesCount); chars = new char[decoder.GetCharCount(data, 0, bytesCount)]; decoder.GetChars(data, 0, bytesCount, chars, 0, true); name = new string(chars); } else { name = "highscore"; } // bytesCount = 9; data = new byte[bytesCount]; fs.Read(data, 0, bytesCount); return(new Highscore(System.BitConverter.ToInt32(data, 0), name, System.BitConverter.ToUInt32(data, 4), (GameEndingType)data[8])); }
private void OnDataReceived(IAsyncResult asyn) { try { int iRx = mSocket.EndReceive(asyn); if (iRx == 0) { ConnectionEnded(); return; } char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.GetEncoding("iso-8859-1").GetDecoder(); int charLen = d.GetChars(dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); NewData(szData); WaitForData(); } catch (ObjectDisposedException) { ConnectionEnded(); return; } catch (SocketException e) { Console.WriteLine("[SCKERR] Error de socket: " + e.ToString()); ConnectionEnded(); } }
void OnDataReceived(IAsyncResult asyn) { try { SocketPacket packet = (SocketPacket)asyn.AsyncState; int end = packet.TCPSocket.EndReceive(asyn); char[] chars = new char[end + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(packet.DataBuffer, 0, end, chars, 0); System.String data = new System.String(chars); ReceiveData(data); WaitForData(); } catch (ObjectDisposedException) { Console.WriteLine("WARNING: Socket closed unexpectedly"); } catch (SocketException se) { if (!_TCPSocket.Connected) { OnDisconnected(se); } } }
/// <summary> Base64 Zip解压 为 byte[] </summary> public static byte[] ZipBase64ToBytes(string xml) { //base64解码 System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] todecode_byte = Convert.FromBase64String(xml); int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length); char[] decoded_char = new char[charCount]; utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0); string decoded = new string(decoded_char); //解压缩 byte[] compressBeforeByte = Convert.FromBase64String(decoded); byte[] buffer = new byte[0x1000]; using (MemoryStream ms = new MemoryStream(compressBeforeByte)) using (var zip = new IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Decompress, true)) using (MemoryStream msreader = new MemoryStream()) { int reader = 0; while ((reader = zip.Read(buffer, 0, buffer.Length)) > 0) { msreader.Write(buffer, 0, reader); } msreader.Position = 0; buffer = msreader.ToArray(); } byte[] compressAfterByte = buffer; return(compressAfterByte); }
/// <summary> /// Call back calling upon recieving the data from the client /// </summary> /// <param name="asyn"></param> private void OnDataReceived(IAsyncResult asyn) { try { CommObject theSocketId = (CommObject)asyn.AsyncState; int iRx = theSocketId.m_WorkScoket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = Encoding.UTF8.GetDecoder(); int charLength = d.GetChars(theSocketId.buffer, 0, iRx, chars, 0); string szData = new string(chars); SetRcvText(szData); // rTbrcvmsg.Text = rTbrcvmsg.Text + szData; WaitForData(); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } }
private string ReceiveData(int BytesReceive, int BufferSize, Socket SocketData) { string Message = string.Empty; if ((BufferSize - BytesReceive) != 0) { while (BytesReceive < BufferSize) { byte[] Buffer = new byte[(BufferSize - BytesReceive)]; int ByteRest = SocketData.Receive(Buffer, (BufferSize - BytesReceive), SocketFlags.None ); char[] charLenght = new char[ByteRest]; System.Text.Decoder decoder = System.Text.Encoding.UTF8.GetDecoder(); decoder.GetChars( Buffer, 0, ByteRest, charLenght, 0 ); BytesReceive += ByteRest; Message += new string(charLenght); } } return(Message); }
public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket socketData = (SocketPacket)asyn.AsyncState; int iRx = 0; // Complete the BeginReceive() asynchronous call by EndReceive() method // which will return the number of characters written to the stream // by the client iRx = socketData.m_currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); //Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => statusText.Inlines.Add("\n")), null); //Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => statusText.Inlines.Add(szData.Length.ToString())), null); Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => statusText.Inlines.Add("\n")), null); Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => statusText.Inlines.Add(szData)), null); // Continue the waiting for data on the Socket WaitForData(socketData.m_currentSocket); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } }
public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String szData = theSockId.string_RemoteEndPoint + ":" + (new System.String(chars)); richTextBox4.Invoke(new UpdateText(updateText), szData); richTextBox4.AppendText("\r\n"); WaitForData(); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (System.Exception se) { //MessageBox.Show("服务器断开连接,请检查服务器然后重新连接!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop); this.richTextBox4.AppendText(se.Message + "\r\n"); button2.PerformClick(); } }
public string ConvertToArabicNumerals(string input) { System.Text.UTF8Encoding utf8Encoder = new UTF8Encoding(); System.Text.Decoder utf8Decoder = utf8Encoder.GetDecoder(); System.Text.StringBuilder convertedChars = new System.Text.StringBuilder(); char[] convertedChar = new char[1]; byte[] bytes = new byte[] { 217, 160 }; char[] inputCharArray = input.ToCharArray(); foreach (char c in inputCharArray) { if (char.IsDigit(c)) { bytes[1] = Convert.ToByte(160 + char.GetNumericValue(c)); utf8Decoder.GetChars(bytes, 0, 2, convertedChar, 0); convertedChars.Append(convertedChar[0]); } else { convertedChars.Append(c); } } return(convertedChars.ToString()); }//end method convert arabic
/// <summary> /// Decode a base64 string (UTF8) /// </summary> /// <param name="encodedValue"></param> /// <returns></returns> public static string Base64Utf8Decode(string encodedValue) { if (String.IsNullOrEmpty(encodedValue)) { return(null); } UTF8Encoding encoder = new UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] todecode_byte = null; try { todecode_byte = Convert.FromBase64String(encodedValue); } catch (FormatException) { return(null); } int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length); char[] decoded_char = new char[charCount]; utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0); return(new String(decoded_char)); }
public static string ConvertToEasternArabicNumerals(string input) { System.Text.UTF8Encoding utf8Encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decoder = utf8Encoder.GetDecoder(); System.Text.StringBuilder convertedChars = new System.Text.StringBuilder(); char[] convertedChar = new char[1]; byte[] bytes = new byte[] { 217, 160 }; char[] inputCharArray = input.ToCharArray(); char[] array = inputCharArray; for (int i = 0; i < array.Length; i++) { char c = array[i]; if (char.IsDigit(c)) { bytes[1] = System.Convert.ToByte(160.0 + char.GetNumericValue(c)); utf8Decoder.GetChars(bytes, 0, 2, convertedChar, 0); convertedChars.Append(convertedChar[0]); } else { convertedChars.Append(c); } } return(convertedChars.ToString()); }
//***** waitForCommand() *****// // Waits for server command and acts accordingly static void waitForCommand() { try { //Console.WriteLine("Waiting for server command"); byte[] buffer = new byte[1024]; int iRx = m_clientSocket.Receive(buffer); char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(buffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); //Console.WriteLine(szData); if (szData.Equals("initialize")) { init(); } else if (szData.Equals("start")) { start(); } else if (szData.Equals("stop")) { stop(); } } catch (SocketException se) { Console.WriteLine(se.Message); } }
private void OnDataReceived(IAsyncResult asyn) { try { int iRx = mSocket.EndReceive(asyn); if (iRx == 0) { ConnectionEnded(); return; } char[] chars = new char[iRx]; System.Text.Decoder d = Encoding.GetEncoding("iso-8859-1").GetDecoder(); int charLen = d.GetChars(dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); NewData(szData); WaitForData(); } catch (ObjectDisposedException) { ConnectionEnded(); } catch (SocketException e) { Logging.LogEvent("Unhandled socket error: " + e.ToString(), Logging.LogLevel.Error); ConnectionEnded(); } }
public String Message(string message) { //initiating Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAdd = System.Net.IPAddress.Parse(ipServer); IPEndPoint remoteEP = new IPEndPoint(ipAdd, 8888); //connect socket socket.Connect(remoteEP); //send message byte[] byData = System.Text.Encoding.ASCII.GetBytes(message); socket.Send(byData); //receiving message byte[] buffer = new byte[1024]; int iRx = socket.Receive(buffer); char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(buffer, 0, iRx, chars, 0); System.String recv = new System.String(chars); socket.Disconnect(false); socket.Close(); //MessageBox.Show(recv); return(recv); }
/// <summary> /// 接收服务端数据回调 /// </summary> /// <param name="ar"></param> private void ReadCallBack(IAsyncResult ar) { //接收到的数据长度 int receLen = 0; SocketError errorCode; try { receLen = m_socket.EndReceive(ar, out errorCode); char[] chars = new char[receLen + 1]; // Extract the characters as a buffer System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(m_dataBuffer, 0, receLen, chars, 0); System.String szData = new System.String(chars); // 构造事件 ItemValueResult[] values = new ItemValueResult[1]; values[0] = new ItemValueResult(); values[0].Value = m_dataBuffer; values[0].ItemName = "MODBUS Client:" + m_socket.LocalEndPoint.ToString(); base.OnDataChange(null, null, values); if (receLen > 0) { string strLogin = "******" + szData; byte[] data = Encoding.ASCII.GetBytes(strLogin); m_socket.BeginSend(data, 0, data.Length, SocketFlags.None, out errorCode, SendCallback, m_dataBuffer);//异步发送数据 //异步接受服务器回报的字符串 m_socket.BeginReceive(m_dataBuffer, 0, m_dataBuffer.Length, SocketFlags.None, ReadCallBack, m_dataBuffer); } } catch (Exception ex) { CLOGException.Trace("函数CommunicationLib.CTcpClientAccess.ReadCallBack 异常", CBaseMethods.MyBase.GetExceptionInfo(ex)); } }
public static string decryptPassword1(string sData) { string result = ""; try { System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] todecode_byte = Convert.FromBase64String(sData); int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length); char[] decoded_char = new char[charCount]; utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0); result = new string(decoded_char); } catch { } return(result); }
public void OnDataReceived(IAsyncResult asyn) { try { CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState; //end receive... int iRx = 0; iRx = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); //txtDataRx.Text = txtDataRx.Text + szData; txtDataRx.AppendText(szData); broadcastData(szData); WaitForData(theSockId.thisSocket); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } }
private void OnDataReceivedC(IAsyncResult asyn) { try { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.m_currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); if (chars[0] == 13) { //SetText(strRXServer); this.OnDataReceivedFinish(this, new EventArgs()); } else { strRXServer += szData.Remove(1, 1); } // textBox1.AppendText(szData); WaitForDataC(); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { //MessageBox.Show(se.Message); } }
public void OnDataReceived(IAsyncResult asyn) { try { CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState; int iRx = 0; iRx = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); ReceiveString = szData; if (ConnectionEventCallBack != null) { ConnectionEventCallBack.Invoke(Enum_ConnectionEventClient.RECEIVEDATA, szData); } Started = true; WaitForData(); } catch (ObjectDisposedException) { //Started = false; } catch (SocketException) { //Started = false; } }
public static string base64Decode(string sData) //Decode { try { var encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] todecodeByte = Convert.FromBase64String(sData); int charCount = utf8Decode.GetCharCount(todecodeByte, 0, todecodeByte.Length); char[] decodedChar = new char[charCount]; utf8Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decodedChar, 0); string result = new String(decodedChar); return(result); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Source); System.Diagnostics.Debug.WriteLine(e.Message); System.Diagnostics.Debug.WriteLine(e.StackTrace); System.Diagnostics.Debug.WriteLine(e.InnerException); Exception f = e.InnerException; while (f != null) { System.Diagnostics.Debug.WriteLine("INNER:"); System.Diagnostics.Debug.WriteLine(f.Message); System.Diagnostics.Debug.WriteLine(f.Source); f = f.InnerException; } System.Diagnostics.Debug.WriteLine(e.Data); return(null); } }
private void OnDataReceived(IAsyncResult asyn) { try { int iRx = 0; iRx = socket.EndReceiveFrom(asyn, ref client); char[] chars = new char[iRx - 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(dataBuffer, 0, iRx - 1, chars, 0); String szData = new System.String(chars); if (szData[0].Equals('*')) { if (szData[1].Equals('C')) { string id = szData.Substring(2); if (!id.Equals(clientID)) { clientID = id; SendData("A\n"); TouchPal.Debug("Client (" + id + ") connected."); manager.ClientConnected(); } } if (szData[1].Equals('R') && manager != null) { manager.ResetControls(); SendData("A\n"); } } else if (manager != null) { string[] controlUpdates = szData.Split(new Char[] { ':' }); foreach (string controlUpdate in controlUpdates) { string[] values = controlUpdate.Split(new Char[] { '=' }); if (values.Count() == 2) { try { int networkID = Convert.ToInt32(values[0]); manager.UpdateControl(networkID, values[1]); SendData("A\n"); } catch (FormatException fe) { TouchPal.Error("Bad network id value (" + values[0] + ") received from client - " + fe.Message); } } } } WaitForData(); } catch (SocketException se) { Console.WriteLine(se.Message); } }
public void OnDataReceived(IAsyncResult asyn) { try { PrintDebug(3, "OnDataReceived"); SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); //printDebug("", szData); ProcessData(szData); if (networkSocket != null && networkSocket.Connected) { WaitForData(); } } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show("onDataReceived exception:" + se.Message); } }
public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); CheckMessage(szData); richTextRxMessage.AppendText(szData); richTextRxMessage.AppendText("\r\n"); richTextRxMessage.SelectionStart = richTextRxMessage.Text.Length; richTextRxMessage.Focus(); tbTotalChar.Text = "" + richTextRxMessage.Text.Length; WaitForData(); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } }
public string Receive() { byte[] buffer = new byte[1024]; int iRx = 0; System.String recv = ""; //exception here when server is dead try { iRx = socket.Receive(buffer); }catch (Exception e) { return(null); } char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(buffer, 0, iRx, chars, 0); recv = new System.String(chars); /* * if (verbose) * { * Log("message received : '" + recv + "', bytes: " + recv.Length); * } */ return(recv); }
public void OnDataReceived(IAsyncResult asyn) { try { CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState; //end receive... int iRx = 0; iRx = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); if (OnDataRecievedEventHandlers != null) { OnDataRecievedEventHandlers(this, new DataRecievedEventArgs(chars)); } WaitForData(m_socWorker); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); ClientDisconnect(); } catch (SocketException se) { System.Diagnostics.Debugger.Log(0, "1", "\n " + se.Message + "\n"); ClientDisconnect(); } }
void OnDataReceived(IAsyncResult async) { SocketPacket socketData = (SocketPacket)async.AsyncState; int iRx = 0; try { iRx = socketData.m_currentSocket.EndReceive(async); if (iRx == 0) { socketData.m_currentSocket.Close(); m_beingUsed[socketData.SocketIndex] = false; Console.WriteLine("Freed:: " + socketData.SocketIndex); } else { char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0); String szData = new String(chars); WaitForData(socketData.m_currentSocket, socketData.SocketIndex); Console.Write(szData); } } catch (SocketException err) { Console.WriteLine(err.Message); } }
public static string base64Decode(string sData) { try { System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] todecode_byte = Convert.FromBase64String(sData); int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length); char[] decoded_char = new char[charCount]; utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0); string result = new String(decoded_char); return(result); } catch (Exception ex) { throw new Exception("Error in base64Decode" + ex.Message); } }
// GetStringFromByteArray metodu byte dizisindeki belli uzunluktaki // bir parçayı alarak, string olarak döndürür. // // bytes: Byte dizisi. // iStart: Byte dizisindeki başlangıç konumu. // iLen: Çevrilecek byte parçasının uzunluğu. // dec: Çevirmede kullanılacak Decoder. public static string GetStringFromByteArray(Byte[] bytes, int iStart, int iLen, Decoder dec) { // Parametrelerin hata kontrolünü yap. if ((iStart + iLen <= bytes.Length) && (iStart >= 0) && (iLen > 0)) { // Karakter dizisi nesnesi oluştur. Char[] chars; // StringBuilder nesnesi oluştur. StringBuilder sb = new StringBuilder(); // GetCharCount metoduyla, byte dizisindeki kodlaması çözülecek // olan byte'lar için gerekli karakter sayısını hesapla. int iCharCount = dec.GetCharCount(bytes, iStart, iLen); // Karakter dizisini boyutlandır. chars = new Char[iCharCount]; // GetChars metoduyla, belirtilen sayı kadar, byte dizisinden // alınan elemanların karakter dizisine çevrilmesi: dec.GetChars(bytes, iStart, iLen, chars, 0); // must skip null-termination of C++ string // Karakter dizisinin sonundaki null kontrolü için: for (int i = 0; i < iCharCount; ++i) { // Konrol karakteri var mı? if (Char.GetUnicodeCategory(chars[i]) != UnicodeCategory.Control) { // Karakter dizini doldur. sb.Append(chars[i].ToString()); } else { break; // Konrol karakteri yakalandı. }//if }//for return sb.ToString(); } else { // Parametrelerde hata bulundu. Boş bir string çevir. return String.Empty; } }
public static string ReadMinimum(this Stream stream, Decoder decoder) { var buffer = new byte[16]; for (int i = 0; i < buffer.Length; ++i) { var read = stream.Read(buffer, i, 1); if (read == 0) { if (i != 0) throw new Exception("invalid encoded text?"); return null; } var charCount = decoder.GetCharCount(buffer, 0, i + 1); if (charCount != 0) { var chars = new char[charCount]; decoder.GetChars(buffer, 0, i + 1, chars, 0); return new string(chars); } } throw new Exception("impossible?"); }
private void FirstRead(byte[] streamData, int readBytes, char[] characters) { Encoding encoding = selector.GetEncoding(streamData); decoder = encoding.GetDecoder(); int theOffset = selector.ByteCount(encoding); int decoded = decoder.GetChars(streamData, theOffset, readBytes - theOffset , characters, 0); myCallbackDelegate(characters, decoded); currentRead = ReadFurther; }
// try to convert the all current test's bytes with Getchars() // in only one step private void DecoderFallbackExceptions_GetChars ( char [] chars, int testno, Decoder dec, DecoderFallbackExceptionTest t) { try { dec.GetChars (t.bytes, 0, t.bytes.Length, chars, 0, true); Assert.IsTrue ( t.eindex.Length == 0, String.Format ( "test#{0}-1: UNEXPECTED SUCCESS", testno)); } catch(DecoderFallbackException ex) { Assert.IsTrue ( t.eindex.Length > 0, String.Format ( "test#{0}-1: UNEXPECTED FAIL", testno)); Assert.IsTrue ( ex.Index == t.eindex[0], String.Format ( "test#{0}-1: Expected exception at {1} not {2}.", testno, t.eindex[0], ex.Index)); Assert.IsTrue ( ex.BytesUnknown.Length == t.elen[0], String.Format ( "test#{0}-1: Expected BytesUnknown.Length of {1} not {2}.", testno, t.elen[0], ex.BytesUnknown.Length)); for (int i = 0; i < ex.BytesUnknown.Length; i++) Assert.IsTrue ( ex.BytesUnknown[i] == t.bytes[ex.Index + i], String.Format ( "test#{0}-1: expected byte {1:X} not {2:X} at {3}.", testno, t.bytes[ex.Index + i], ex.BytesUnknown[i], ex.Index + i)); dec.Reset (); } }
private int GetCharsFromStream(Stream inputStream, int count, Decoder decoder, char[] chars) { // Now, read just the field value. PGUtil.CheckedStreamRead(inputStream, _inputBuffer, 0, count); int charCount = decoder.GetCharCount(_inputBuffer, 0, count); decoder.GetChars(_inputBuffer, 0, count, chars, 0); return charCount; }
private int IntReadChars(char[] buffer, int index, int count, Encoding encode, Decoder decoder) { int cpS = 1; if (encode is UnicodeEncoding) { cpS = 2; } else if (encode is UTF32Encoding) { cpS = 4; } int rem = count; while (rem > 0) { int read = Math.Min(rem*cpS, _bufferLength); read = _stream.Read(_buffer, 0, read); if (read == 0) { return count - rem; } read = decoder.GetChars(_buffer, 0, read, buffer, index); rem -= read; index += read; } return count; }