Byte [] to int conversion impossible - c#

And the problem I have, when converting Byte[] to String, I tried with the Encoding.UTF8.GetString and the ncoding.Ascii.GetString but nothing changes ???
I always end up with a string that has backslashes in this form
sRecv = "\\0\\0\\0u0001"
I don't understand....
Sender code
public void SendDatas(int progress)
{
byte[] intBytes = BitConverter.GetBytes(progress);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;
try
{
_socketClient.Send(result, SocketFlags.None);
}
catch
{
MessageBox.Show($"Erreur lors de la transmition des données", "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
receive code
public int EcouterReseau(Socket socketClient)
{
string sRecv;
try
{
byte[] data = new byte[1024];
int recv = socketClient.Receive(data);
sRecv = Encoding.Unicode.GetString(data, 0, recv);
}
catch
{
sRecv = "0";
}
int returnValue = int.Parse(sRecv.Remove(0, 7));
return returnValue;
}

Related

C# Client.SendFile() separating stream

Please bear in mind I am new to C# language and networking so forgive me if this might sound obvious.
I'm just in the process of understanding TCP clients and how to separate streams...
In this example, I have 3 sets of data that I want to send...
is a CMD output:
private void CmdOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
StringBuilder strOutput = new StringBuilder();
if (!String.IsNullOrEmpty(outLine.Data))
{
try
{
strOutput.Append(outLine.Data);
buffer = encoder.GetBytes("2 " + outLine.Data+ "\r\n");
networkStream = newclient.GetStream();
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Flush();
}
catch (Exception err) { }
}
}
Which returns as a first stream the following:
With a prebuffer as number 2(To separate the data)
The second Is a simple get info:
private void GetClientinfo()
{
networkStream = newclient.GetStream();
buffer = encoder.GetBytes("1 " + Environment.MachineName +"\n"+"Connected");
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Flush();
}
Which then sends the following :
So then my stream ends up being separated:
My issue is then that I try to send a file with the following script:
private void sendFile()
{
// Create the preBuffer data.
string string1 = String.Format("9 ");
byte[] preBuf = Encoding.ASCII.GetBytes(string1);
// Create the postBuffer data.
string string2 = String.Format("");
byte[] postBuf = Encoding.ASCII.GetBytes(string2);
string filePath = #"\Users\nico_\Documents\transfer_ex.txt";
newclient.Client.SendFile(filePath, preBuf, postBuf, TransmitFileOptions.UseDefaultWorkerThread);
}
As you can see, it ends up getting jumbled up with the second stream being sent...
What would be the cause of this?
FULL SERVER SCRIPT:
public partial class Form1 : Form
{
TcpListener tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
private int appStatus = 0;
TcpClient client;
TcpClient streamData;
List<TcpClient> clientList = new List<TcpClient>();
NetworkStream networkStream;
Thread th_StartListen, th_handleClient;
StringBuilder strOutput;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
th_StartListen = new Thread(new ThreadStart(StartListen));
th_StartListen.Start();
txtCmdOutput.Focus();
}
private void StartListen()
{
//Creating a TCP Connection and listening to the port
tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
tcpListener.Start();
toolStripStatusLabel1.Text = "Listening on port 6666 ...";
int counter = 0;
appStatus = 0;
while (appStatus != 2)
{
try
{
client = tcpListener.AcceptTcpClient();
counter++;
clientList.Add(client);
IPEndPoint ipend = (IPEndPoint)client.Client.RemoteEndPoint;
//Updating status of connection
toolStripStatusLabel1.Text = "Connected from "+ IPAddress.Parse(ipend.Address.ToString());
appStatus = 1;
th_handleClient = new Thread(delegate () { handleClient(client, counter); });
th_handleClient.Start();
}
catch (Exception err)
{
{
Cleanup();
}
}
}
}
private void handleClient(object client, int i)
{
try
{
TcpClient streamData = (TcpClient)client;
byte[] data = new byte[4096];
byte[] sendData = new byte[4096];
int byteRead;
string strdata;
ASCIIEncoding encode = new ASCIIEncoding();
Thread.Sleep(2000);
NetworkStream networkstream = streamData.GetStream();
//Send Command 1
sendData = encode.GetBytes("1");
networkstream.Write(sendData, 0, sendData.Length);
networkstream.Flush();
//Listen...
while (true)
{
byteRead = 1;
byteRead = networkstream.Read(data, 0, 4096);
//receiveFile();
if (networkstream.DataAvailable != true)
{
strdata = Encoding.ASCII.GetString(data, 0, byteRead);
Debug.WriteLine(strdata);
//Get user info
if (strdata.StartsWith("1"))
{
updateLabel(labelMachinename, strdata, 0);
updateLabel(labelSampleOutput, strdata, 1);
}
if (strdata.StartsWith("2"))
{
updateText(txtCmdConsole, strdata);
}
if (strdata.StartsWith("9"))
{
Debug.WriteLine(strdata);
}
//receiveFile();
}
}
}
catch (Exception err)
{
{
Cleanup();
}
}
}
private void receiveFile()
{
StreamReader reader = new StreamReader(client.GetStream());
string fileSize = reader.ReadLine();
string fileName = reader.ReadLine();
int length = Convert.ToInt32(fileSize);
byte[] buffer = new byte[length];
int received = 0;
int read = 0;
int size = 1024;
int remaining = 0;
while (received < length)
{
remaining = length - received;
if (remaining < size)
{
size = remaining;
}
read = client.GetStream().Read(buffer, received, size);
received += read;
}
// Save the file using the filename sent by the client
using (FileStream fStream = new FileStream(Path.GetFileName(fileName), FileMode.Create))
{
fStream.Write(buffer, 0, buffer.Length);
fStream.Flush();
fStream.Close();
}
Debug.WriteLine("File received and saved in " + Environment.CurrentDirectory);
}
private void txtCmdOutput_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter && appStatus == 1)
{
TcpClient streamData = (TcpClient)client;
byte[] sendData = new byte[4096];
ASCIIEncoding encode = new ASCIIEncoding();
NetworkStream networkstream = streamData.GetStream();
sendData = encode.GetBytes("2 "+ txtCmdOutput.Text.ToString());
networkstream.Write(sendData, 0, sendData.Length);
networkstream.Flush();
txtCmdOutput.Text = "";
}
}
catch (Exception err) {
{
Cleanup();
}
}
}
private void updateLabel(Label label,string strdata, int row)
{
label.Invoke((MethodInvoker)delegate
{
label.Text = strdata.Substring(2).Split(new char[] { '\r', '\n' })[row];
});
}
private void updateText(TextBox text, string strdata)
{
text.Invoke((MethodInvoker)delegate
{
text.AppendText(strdata.Substring(2));
});
}
private void btnKillClient_Click(object sender, EventArgs e)
{
try
{
TcpClient streamData = (TcpClient)client;
byte[] sendData = new byte[4096];
ASCIIEncoding encode = new ASCIIEncoding();
NetworkStream networkstream = streamData.GetStream();
sendData = encode.GetBytes("3");
networkstream.Write(sendData, 0, sendData.Length);
networkstream.Flush();
Cleanup();
}
catch (Exception err)
{
{
Cleanup();
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
private void Cleanup()
{
try
{
toolStripStatusLabel1.Text = "Connection Lost";
}
catch (Exception err) { }
}
}
FULL CLIENT SCRIPT:
public partial class Form1 : Form
{
private int appStatus = 0;
TcpClient newclient = new TcpClient();
NetworkStream networkStream;
byte[] buffer = new byte[4096];
ASCIIEncoding encoder = new ASCIIEncoding();
Process processCmd;
Thread th_ListenToServer, th_RunServer;
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
this.Hide();
th_ListenToServer = new Thread(new ThreadStart(ListenToServer));
th_ListenToServer.Start();
//ConnectToServer();
}
private void ListenToServer()
{
while (!newclient.Connected)
{
try
{
newclient = new TcpClient();
Debug.WriteLine("trying to connect...");
newclient = new TcpClient("127.0.0.1", 6666);
networkStream = newclient.GetStream();
th_RunServer = new Thread(new ThreadStart(RunServer));
th_RunServer.Start();
}
catch (Exception ex)
{
Debug.WriteLine("Could not connect to server");
System.Threading.Thread.Sleep(5000); //Wait 5 seconds then try again
}
}
}
private void RunServer()
{
byte[] data = new byte[4096];
int i;
string strdata;
i = 0;
CmdHandler();
sendFile();
while (newclient.Connected)
{
try
{
i = 0;
i = networkStream.Read(data, 0, data.Length);
if (i == 0) { break; }
strdata = Encoding.ASCII.GetString(data, 0, i);
Debug.WriteLine(strdata);
if (strdata == "1")
{
GetClientinfo();
}
if (strdata.StartsWith("2"))
{
//Debug.WriteLine(strdata);
processCmd.StandardInput.WriteLine(strdata.Substring(2));
}
if (strdata.StartsWith("3"))
{
StopServer();
}
if (strdata.StartsWith("4"))
{
StopServer();
}
else
{
//sendFile();
}
}
catch
{
Cleanup();
new Thread(ListenToServer).Start();
Debug.WriteLine("Attempting Reconection");
}
}
}
private void sendFile()
{
/*
// Create the preBuffer data.
string fileName = #"\Users\nico_\Documents\transfer_ex.txt";
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] fileNameLen= BitConverter.GetBytes(fileNameByte.Length);
byte[] fileData = File.ReadAllBytes(fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
networkStream = newclient.GetStream();
buffer = encoder.GetBytes("9 " + clientData);
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Flush();
*/
string string1 = String.Format("9 ");
byte[] preBuf = Encoding.ASCII.GetBytes(string1);
// Create the postBuffer data.
string string2 = String.Format("");
byte[] postBuf = Encoding.ASCII.GetBytes(string2);
string filePath = #"\Users\nico_\Documents\transfer_ex.txt";
newclient.Client.SendFile(filePath, preBuf, postBuf, TransmitFileOptions.UseDefaultWorkerThread);
}
private void GetClientinfo()
{
networkStream = newclient.GetStream();
buffer = encoder.GetBytes("1 " + Environment.MachineName + "\n" + "Connected");
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Flush();
}
private void CmdHandler()
{
processCmd = new Process();
processCmd.StartInfo.FileName = "cmd.exe";
processCmd.StartInfo.CreateNoWindow = true;
processCmd.StartInfo.UseShellExecute = false;
processCmd.StartInfo.RedirectStandardOutput = true;
processCmd.StartInfo.RedirectStandardInput = true;
processCmd.StartInfo.RedirectStandardError = true;
//processCmd.OutputDataReceived += CaptureOutput;
//processCmd.ErrorDataReceived += CaptureError;
processCmd.OutputDataReceived += new DataReceivedEventHandler(CmdOutputDataHandler);
processCmd.ErrorDataReceived += new DataReceivedEventHandler(CmdOutputDataHandler);
processCmd.Start();
processCmd.BeginOutputReadLine();
}
private void CmdOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
StringBuilder strOutput = new StringBuilder();
if (!String.IsNullOrEmpty(outLine.Data))
{
try
{
strOutput.Append(outLine.Data);
buffer = encoder.GetBytes("2 " + outLine.Data + "\r\n");
networkStream = newclient.GetStream();
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Flush();
}
catch (Exception err) { }
}
}
private void Cleanup()
{
try { processCmd.Kill(); } catch (Exception err) { };
networkStream.Close();
}
private void StopServer()
{
Cleanup();
System.Environment.Exit(System.Environment.ExitCode);
}
}
Your first output appends \r\n, which results in separation from the second output. The second output embeds a \n (not \r\n) and ends with nothing, which means nothing separates it from the third output.
Either add a newline after data in GetClientInfo, or add one to preBuf in sendFile().
Or switch to something less ambiguous, like length-prefixing.
Here is the answer:
CLIENT SIDE:
private void sendFile()
{
string string1 = "9";
byte[] preBuf = Encoding.ASCII.GetBytes(string1);
// Create the postBuffer data.
string string2 = "";
byte[] postBuf = Encoding.ASCII.GetBytes(string2);
string filePath = #"\Users\nico_\Documents\transfer_ex.txt";
newclient.Client.SendFile(filePath, preBuf, postBuf, TransmitFileOptions.UseDefaultWorkerThread);
}
SERVER SIDE:
private void ReceiveFile(byte[] data, int byteRead)
{
var path = #"\Users\nico_\Documents\transferreeedd_ex.txt";
FileStream fs = File.OpenWrite(path);
//Debug.WriteLine(byteRead);
//Debug.WriteLine(data);
string ddstrdata = Encoding.ASCII.GetString(data, 0, byteRead);
for (int i = 1; i < byteRead; i++)
{
Debug.WriteLine(i);
fs.WriteByte(data[i]);
}
fs.Close();
}
If you dont use any separtators, on newclient.Client.SendFile you can just put the Filepath and on Server side int i = 0 & not int i = 1

The input stream is not a valid binary format Tcp

I have 2 method they look and work very similarly. Dont know why first method work but second dont. Secound throw Exeption "The input stream is not a valid binary format Tcp" This method send object by tcp from client to server and from server to client.
Can sameone tell me what am I doing wrong?
public static void SendComput(NetworkStream stream)
{
string id = "1";
Byte[] datasend = System.Text.Encoding.ASCII.GetBytes(id);
BinaryFormatter formatter = new BinaryFormatter();
stream.Write(datasend, 0, datasend.Length);
Console.WriteLine("Sent: {0}", id);
while (true)
{
try
{
var data = new Byte[256];
String response = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
response = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", response);
}
catch (Exception e)
{
throw;
}
try
{
var t = GetComputeUnitsPerf();
var t2 = new Comp();
t2.ComputeTime = (uint)t.TimeMilisceoncd;
t2.DateCheck = t.Date;
t2.Id = Int32.Parse(id);
formatter.Serialize(stream,t2);
Console.WriteLine("Sent: {0}, {1}, {2}", t2.Id , t2.ComputeTime, t2.DateCheck);
Thread.Sleep(100);
}
catch (Exception e)
{
throw;
}
}
}
And server:
public void HandleDeivce3(Object obj)
{
TcpClient client = (TcpClient)obj;
var stream = client.GetStream();
Byte[] bytes = new Byte[256];
int i = 0;
string data = null;
BinaryFormatter formatter = new BinaryFormatter();
Task.Run(() =>
{
string hex = BitConverter.ToString(bytes);
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
while (true)
{
Thread.Sleep(10000);
Byte[] reply = System.Text.Encoding.ASCII.GetBytes("Send");
stream.Write(reply, 0, reply.Length);
Console.WriteLine("Send");
Thread.Sleep(200);
try
{
if (stream.CanRead)
{
var dataGet = (Comp)formatter.Deserialize(stream);
//Console.WriteLine("Sent: {0}, {1}, {2}", dataGet.Id, dataGet.ComputeTime, dataGet.DateCheck);
Console.WriteLine(dataGet.Id);
}
}
catch (Exception e)
{
throw;
}
}
});
}
I add [Serializable] to Comp class.

How can I make each flush() work, which make each buffer sent before next write() in C#

I am trying to sent very screenshot when i move the mouse on the screen. Therefore, I will sent the size of screenshot and image byte[]. In my client side, I will set the size byte array by the size received from server, and read the rest of byte[] as image. Ideally, I need each time I call the write(), the byte[] I want write into should be empty, so I use the flush(). In fact, after I received the getinputstream(), Sometime I will get the old data inside it. I don't know why flush() doesn't work. anyone has better ideas to solve this problem?
This is my code for server, I try use stream, and networkstream, it dosent works.
public void send(byte[] imageByte)
{
Stream stream = client.GetStream();
client.NoDelay = true;
client.Client.NoDelay = true;
Debug.WriteLine("noDelay:{0}, client.noDelay:{1}", client.NoDelay, client.Client.NoDelay);
byte[] imageSize;
string imgSize = Convert.ToString(imageByte.Length);
Debug.WriteLine("string=" + imgSize);
imageSize = Encoding.ASCII.GetBytes(imgSize);
Debug.WriteLine(" header size:" + imageSize.Length);
//ns.Write(imageSize, 0, imageSize.Length);
//ns.Flush();
//sleep 500 ms
stream.Write(imageSize, 0, imageSize.Length);
stream.Flush();
Thread.Sleep(150);
Debug.WriteLine("sent size");
//ns.Write(imageByte, 0, imageByte.Length);
//ns.Flush();
stream.Write(imageByte, 0, imageByte.Length);
stream.Flush();
Debug.WriteLine("First time sent image size:" + imageByte.Length);
client side:
public class connection extends AsyncTask {
private byte[] data;
public void setByteSize(int size) {
data = new byte[size];
}
public byte[] getByteSize() {
return data;
}
#Override
protected Object doInBackground(Object... arg0) {
try {
clientSocket = new Socket("134.129.125.126", 8080);
// clientSocket = new Socket("134.129.125.172", 8080);
System.out.println("client connect to server");
input = clientSocket.getInputStream();
System.out.println("getinputstream");
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
int totalBytesRead = 0;
int chunkSize = 0;
int tempRead = 0;
String msg = null;
// byte[] data = null;
byte[] tempByte = new byte[1024 * 1024 * 4];
try {
// read from the inputstream
tempRead = input.read(tempByte);
// tempbyte has x+5 byte
System.out.println("Fist time read:" + tempRead);
// convert x+5 byte into String
String message = new String(tempByte, 0, tempRead);
msg = message.substring(0, 5);
int msgSize = Integer.parseInt(msg);
data = new byte[msgSize];
// for(int i =0;i<tempRead-5;i++)
// {
// data[i]=tempByte[i+5];
// }
for (int i = 0; i < msgSize; i++) {
data[i] = tempByte[i + 5];
}
// cut the header into imageMsg
// String imageMsg = new String(tempByte, 5, tempRead - 5);
// convert string into byte
System.out.println("message head:" + msg);
byteSize = Integer.parseInt(msg);
System.out.println("ByteSize:" + byteSize);
// convert String into byte[]
totalBytesRead = tempRead - 5;
System.out.println("total Byte Read=" + totalBytesRead);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// get string for the size of image
try {
while (totalBytesRead != getByteSize().length) {
System.out.println("data length:"
+ getByteSize().length);
chunkSize = input.read(getByteSize(), totalBytesRead,
getByteSize().length - totalBytesRead);
System.out.println("chunkSize is " + chunkSize);
totalBytesRead += chunkSize;
// System.out.println("Total byte read "
// + totalBytesRead);
}
System.out.println("Complete reading - total read = "
+ totalBytesRead);
} catch (Exception e) {
}
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
System.out.println("deco");
runOnUiThread(new Runnable() {
public void run() {
image.setImageBitmap(bitmap);
System.out.println("setImage at less than 500");
}
});
}
}
}

stringToHex and hexToString C# anf Android Java

here are the whole story:
(1) I have string "123";
(2) Encrypt to "????g*Ox*??D#?\v" using EncryptFromBase64;
(3) Converted to hex string using ConvertStringToHex
Here is the C# code.
public string ConvertStringToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int value = Convert.ToInt32(c);
// Convert the decimal value to a hexadecimal value in string form.
hex += String.Format("{0:X2}", value);
}
return hex;
}
public string ConvertHexToString(string HexValue)
{
string StrValue = "";
while (HexValue.Length > 0)
{
StrValue += System.Convert.ToChar(System.Convert.ToUInt32(HexValue.Substring(0, 2), 16)).ToString();
HexValue = HexValue.Substring(2, HexValue.Length - 2);
}
return StrValue;
}
public string Encrypt(byte[] encryptedData)
{
byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.ASCII.GetString(newClearData);
}
public string EncryptFromBase64(string encryptedBase64)
{
if (encryptedBase64.Length < 1) return "";
byte[] bytes = Encoding.ASCII.GetBytes(encryptedBase64);
return Encrypt(bytes);
}
(4)The hex string is then transported to Android request command to C# web service and converted back to string. using convertHexToString
(5) Decryt using decryptAsBase64. There is padding exception.
Here is the android code.
public String decryptAsBase64(String clearData) {
if(clearData.length() < 1) return "";
byte[] encryptedData = clearData.getBytes();
byte[] decryptedData = decryptAsBase64(encryptedData);
String str = Base64.encodeBytes(decryptedData);
str = str.replace("+", "%2B");
return str;
}
public byte[] decryptAsBase64(byte[] clearData) {
byte[] decryptedData =decrypt(clearData);
try {
return Base64.decode(decryptedData);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return decryptedData;
}
public byte[] decrypt(byte[] clearData) {
byte[] decryptedData;
try {
decryptedData = aesCipher_Decoder.doFinal(clearData);
} catch (IllegalBlockSizeException e) {
Log.e(TAG, "Illegal block size", e);
return null;
} catch (BadPaddingException e) {
Log.e(TAG, "Bad padding", e);
return null;
}
return decryptedData;
}
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
}
return sb.toString();
}
The string converted back "????g*Ox*??D#?" is incorrect.
Anything wrong with my code?
You're grabbing the hex characters in pairs in your convertHexToString() method, but your {0:X} format string doesn't necessarily output 2 hex digits per character. If you want to make sure each character is represented by 2 hex digits, then use this format string instead:
{0:X2}
The problem was resolved. The error is in the encryption and decryption codes. The following code
public string Encrypt(byte[] encryptedData)
{
byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.ASCII.GetString(newClearData);
}
should be
public string Encrypt(byte[] encryptedData)
{
byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
// return Encoding.ASCII.GetString(newClearData);
return Convert.ToBase64String(newClearData);
}
In the android decryption code. The code
public String decryptAsBase64(String clearData) {
if(clearData.length() < 1) return "";
byte[] encryptedData = clearData.getBytes();
byte[] decryptedData = decryptAsBase64(encryptedData);
String str = Base64.encodeBytes(decryptedData);
str = str.replace("+", "%2B");
return str;
}
should be
public String decryptAsBase64(String clearData) {
if(clearData.length() < 1) return "";
byte[] encryptedData = null;
try {
encryptedData = Base64.decode(clearData);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] decryptedData = decrypt(encryptedData);
String str = null;
try {
str = new String(decryptedData, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}

Delay 3mins at the start of the program why? socket programming in C#

I will get 3mins of delay at the start of the below program.but where as in hyper terminal it shows every data for every 2 secs.
Her is my below code.please let me know where i went wrong .How i can rectify this delay. any suggestion?
private void StartReceiving()
{
// coding part of receiving changed.
try
{
string IPStr = textBox1_IPaddress.Text.Trim();
string portStr = textBox2_Port.Text.Trim();
int port = Convert.ToInt32(portStr);
int bytesRead = 0;
byte[] buffer = new byte[9];
//------------------------------------------------------------------
IPAddress ipAddress = System.Net.IPAddress.Parse(IPStr);
//create server's tcp listener for incoming connection
try
{
textBox3.Visible = true;
client = new TcpClient();
client.Connect(IPStr, port);
ns = client.GetStream();
while (true)
{
if (ns.DataAvailable)
{
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
textBox3.AppendText(msg);
textBox3.AppendText("\n");
GetData(msg);
}
else
{
Thread.Sleep(4000);
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
GetData(msg);
}
}
client.Close();
}
catch (SocketException se)
{
//message box;
}
}
}
public static byte[] ReadNumberBytes(NetworkStream stream, int n)
{
byte[] buffer = new byte[n];
int bytesRead = 0;
int chunk;
while (bytesRead < n)
{
chunk = stream.Read(buffer, (int)bytesRead, buffer.Length - int)bytesRead);
if (chunk == 0)
{
// error out.
throw new Exception("Unexpected disconnect");
}
bytesRead += chunk;
}
return buffer;
}

Categories