I developed a listener that receives data every 60 seconds, It is receiving data as XML Data Stream, which is complete XML. In most cases it is working fine, saving complete XML into a single file of 4 kb. However, Sometimes it is saving one complete XML into 2 files. I am not getting why this is happening.
My code is below. Kindly help.
public static void GetXMLStream()
{
TcpListener server = null;
try
{
Int32 port = Int32.Parse(GetAppConfigValues.GetAppConfigValue("Port"));
IPAddress localAddr = IPAddress.Parse(GetAppConfigValues.GetAppConfigValue("IPAddress"));
server = new TcpListener(localAddr, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
WriteToFile(data);
}
}
}
catch (SocketException e)
{}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
public static void WriteToFile(string sMessage)
{
try
{
string fileName = "NiproMI" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_") + ".xml";
DirectoryInfo logdirFile = new DirectoryInfo(System.Configuration.ConfigurationManager.AppSettings["XmlFilePath"].ToString());
string filePath = logdirFile.FullName;
if (File.Exists(Path.Combine(filePath, fileName)))
{
StreamWriter sw = null;
FileStream fs = File.Open(Path.Combine(filePath, fileName), FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(sMessage);
sw.Close();
sw = null;
}
else
{
StreamWriter sw = null;
FileStream fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(sMessage);
sw.Close();
sw = null;
}
}
catch (Exception e)
{
NiproEventsLog.WriteLog(e.ToString());
}
}
You should lift the file name out from WriteToFile, because one call of GetXMLStream should have only 1 file name.
Something like this:
public static void GetXMLStream()
{
string fileName = "NiproMI" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_") + ".xml";
TcpListener server = null;
try
{
Int32 port = Int32.Parse(GetAppConfigValues.GetAppConfigValue("Port"));
IPAddress localAddr = IPAddress.Parse(GetAppConfigValues.GetAppConfigValue("IPAddress"));
server = new TcpListener(localAddr, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
WriteToFile(data, fileName);
}
}
}
catch (SocketException e)
{
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
public static void WriteToFile(string sMessage, string fileName)
{
try {
DirectoryInfo logdirFile = new DirectoryInfo(System.Configuration.ConfigurationManager.AppSettings["XmlFilePath"].ToString());
string filePath = logdirFile.FullName;
if (File.Exists(Path.Combine(filePath, fileName)))
{
StreamWriter sw = null;
FileStream fs = File.Open(Path.Combine(filePath, fileName), FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(sMessage);
sw.Close();
sw = null;
}
else
{
StreamWriter sw = null;
FileStream fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(sMessage);
sw.Close();
sw = null;
}
}
catch (Exception e)
{
NiproEventsLog.WriteLog( e.ToString());
}
}
Related
Our Client have a dialysis machine which use Ethernet TCP/IP Protocol and data transfer protocol is XML.It automatically connects to the our computer system by using the configured IP address and port number and sends unsolicited data messages every 60 seconds to our system. Client send data as XML Data Stream. Now I need to store data in XML file.
Below is my code.
Here now problem is, Client is sending data messages from four machines, However my code is capturing data from only one machine, Kindly suggest what I am missing here.
namespace NiproMI
{
class NiproListener
{
public static void GetXMLStream()
{
TcpListener server = null;
try
{
Int32 port = Int32.Parse(AppConfigValues.GetAppConfigValue("Port"));
IPAddress localAddr = IPAddress.Parse(AppConfigValues.GetAppConfigValue("IPAddress"));
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
string fileName = "NiproMI_" + DateTime.Now.ToString("dd-MM-yyyy--HH-mm-ss-ffff") + ".xml";
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
WriteToFile(data, fileName);
if (data.Contains("</Rec>"))
{
MoveInputFile(fileName);
fileName = "NiproMI_" + DateTime.Now.ToString("dd-MM-yyyy--HH-mm-ss-ffff") + ".xml";
}
}
}
}
catch (SocketException e)
{
MIEventLogs.WriteLog("SocketException: {0}" + e);
}
finally
{
server.Stop();
}
}
public static void WriteToFile(string sMessage, string fileName)
{
try {
DirectoryInfo logdirFile = new DirectoryInfo(System.Configuration.ConfigurationManager.AppSettings["XmlFilePath"].ToString());
string filePath = logdirFile.FullName;
if (File.Exists(Path.Combine(filePath, fileName)))
{
StreamWriter sw = null;
//Open File
FileStream fs = File.Open(Path.Combine(filePath, fileName), FileMode.Append, FileAccess.Write);
// generate a file stream with UTF8 characters
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(sMessage);
sw.Close();
sw = null;
}
else
{
StreamWriter sw = null;
//Open File
FileStream fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write);
// generate a file stream with UTF8 characters
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(sMessage);
sw.Close();
sw = null;
}
}
catch (Exception e)
{
MIEventLogs.WriteLog( e.ToString());
}
}
private static void MoveInputFile(string sFileName)
{
string strSourceFullFileName = "";
string strDestFullFilename = "";
string movedFromFolder= AppConfigValues.GetAppConfigValue("XmlFilePath");
string movedToFolder = AppConfigValues.GetAppConfigValue("InputPath");
System.IO.DirectoryInfo objdestfolder = new System.IO.DirectoryInfo(movedToFolder);
System.IO.DirectoryInfo getsourceFile = new System.IO.DirectoryInfo(movedFromFolder);
string sourcePath = "";
string DestPath = "";
try
{
sourcePath = getsourceFile.FullName;
if (sourcePath[sourcePath.Length - 1] != '\\')
sourcePath += "\\";
if (File.Exists(sourcePath + sFileName))
strSourceFullFileName = sourcePath + sFileName;
DestPath = objdestfolder.FullName;
if (DestPath[DestPath.Length - 1] != '\\')
DestPath += "\\";
strDestFullFilename = DestPath + sFileName;
if ((File.Exists(strSourceFullFileName) == true) && (objdestfolder.Exists == true))
{
if (File.Exists(strDestFullFilename))
{
File.Delete(strDestFullFilename);
}
File.Move(strSourceFullFileName, strDestFullFilename);
}
else
{
throw new System.ApplicationException("Invalid destination folder to move retry file.");
}
}
catch (System.Exception ex)
{
}
finally
{
}
}
}
}
You need to hand off the client to another thread or task while you wait for a new client.
I suggest you change this code to be fully asynchronous, using tasks and await. Something like this should work.
public static Task GetXMLStream(CancellationToken cancel)
{
Int32 port = Int32.Parse(AppConfigValues.GetAppConfigValue("Port"));
IPAddress localAddr = IPAddress.Parse(AppConfigValues.GetAppConfigValue("IPAddress"));
using (var server = new TcpListener(localAddr, port))
{
server.Start();
while (!cancel.IsCancellationRequested)
{
TcpClient client = await server.AcceptTcpClientAsync(cancel);
Task.Run(async () => await ProcessClient(client, cancel));
}
server.Stop();
}
}
private static async Task ProcessClient(TcpClient client, CancellationToken cancel)
{
using (client)
using (NetworkStream stream = client.GetStream())
{
try
{
await LoopClientStream(stream, cancel);
}
catch (OperationCanceledException)
{ //
}
catch (SocketException e)
{
MIEventLogs.WriteLog("SocketException: {0}" + e);
}
}
}
Your code that reads the stream and writes it to a file should also be fully asynchronous. I will leave that to you. Make sure you pass the CancellationToken to each asynchronous function.
You should also be aware that the stream may not return </Rec> in a single read, it may be split over separate reads. You may want to find a better way of tracking the end of each packet of data
My code as follows:
static void Main(string[] args)
{
TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 8081);
listener.Start();
Console.WriteLine("- Waiting for a connection..... .");
TcpClient client = listener.AcceptTcpClient();
while (true)
{
//Console.WriteLine("Waiting for a connection.");
//TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client accepted.");
NetworkStream stream = client.GetStream();
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
try
{
byte[] buffer = new byte[4096];
stream.Read(buffer, 0, buffer.Length);
int recv = 0;
foreach (byte b in buffer)
{
if (b != 0)
{
recv++;
}
}
string data = Encoding.UTF8.GetString(buffer, 0, recv);
//
var result = data.Split(new string[] { cr }, StringSplitOptions.None);
System.Threading.Thread.Sleep(1000);
sw.WriteLine("Hello Client, This is server");
sw.Flush();
sw.WriteLine works just fine here, but when I try to call it from another function
public static void Send()
{
sw.Writeline("Sending this from send function");
}
I get an error saying
(Error 9 The name 'sw' does not exist in the current context).
I couldn't figure out the right way to call it since sw StreamWriter uses stream() and stream uses (client) while the client uses (listener), this got beyond my very humble understanding of c#, I spent 2 days trying and researching before posting but with no luck.
Thanks
You are defining the StreamWriter in the scope of the while loop. Outside of it it does not exist. Try defining the StreamWriter as a parameter part of the class and only assign it later.
Change this:
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
To This:
static StreamReader sr = null;
static StreamWriter sw = null;
static void Main(string[] args)
{
...
while (true){
...
sr = new StreamReader(client.GetStream());
sw = new StreamWriter(client.GetStream());
}
}
Java (client side)
relevant code
// Create the encoder and decoder for targetEncoding
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
byte[] underlyingBuffer = new byte[100000];
ByteBuffer buffer = ByteBuffer.wrap(underlyingBuffer);
System.out.println("first buffer remaining" + buffer.remaining() + " "
+ buffer.limit());
buffer.order(ByteOrder.LITTLE_ENDIAN);
try {
Socket client = new Socket("localhost", 8080);
OutputStream oStream = client.getOutputStream();
InputStream iStream = client.getInputStream();
//String secondFilePath = "C:\\Users\\pedge\\Desktop\\readData.csv";//this is csv file
//long secondFileLength = ReadFileToCharArray(buffer,secondFilePath , encoder);
String inputImage = "C:\\Users\\pedge\\Desktop\\Desert.jpeg";// image to transfer
ReadFileToCharArray(buffer,inputImage , encoder);
//imageWrite(oStream, inputImage);
buffer.flip();
int dataToSend = buffer.remaining();
int remaining = dataToSend;
while (remaining > 0) {
oStream.write(buffer.get());
--remaining;
}
public static long ReadFileToCharArray(ByteBuffer buffer, String filePath,
CharsetEncoder encoder) throws IOException {
fileCount++;
System.out.println("second buffer remaining" + buffer.remaining() + " "
+ buffer.limit());
StringBuilder fileData = new StringBuilder(100);
File file = new File(filePath);
System.out.println("Size of file ["+fileCount+"] sent is ["+file.length()+"]");
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[10000000];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
System.out.println(numRead);
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1000000];
}
reader.close();
CharBuffer charBuffer = CharBuffer.wrap(fileData.toString()
.toCharArray());
System.out.println("char buffer " + charBuffer.remaining());
ByteBuffer nbBuffer = null;
try {
nbBuffer = encoder.encode(charBuffer);
} catch (CharacterCodingException e) {
throw new ArithmeticException();
}
buffer.putInt(nbBuffer.limit());
System.out.println("buffer information" + buffer.position() + " "
+ buffer.limit() + " nbBuffer information" + nbBuffer.position()
+ " " + nbBuffer.limit());
buffer.put(nbBuffer);
return file.length();
}
C# (Server Side)
static void Main(string[] args)
{
try
{
Run(args);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
static void Run(string[] args)
{
TcpListener listener = new TcpListener(8080);
listener.Start();
while (true)
{
using (TcpClient client = listener.AcceptTcpClient())
{
try
{
Read(client);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
}
}
static void Read(TcpClient client)
{
String csvFile4Parsing = "C:\\Users\\pedge\\Desktop\\newReadData.csv";// csv file created from byte stream
Console.WriteLine("Got connection: {0}", DateTime.Now);
NetworkStream ns = client.GetStream();
BinaryReader reader = new BinaryReader(ns);
int length = reader.ReadInt32();
Console.WriteLine("Length of csv is [" + length + "]");
byte[] fileArray = reader.ReadBytes(length);
File.WriteAllBytes(csvFile4Parsing, fileArray);//bytes from stream, written to csv`
Now i am able to transfer the image from java to C# and a file is then created by c#(works perfect)
But when i try to send the image(same as like CSV), it doesn't work at all and even the bytes received at the server end are different from that of client end. I have spent hours now on this with no success. :/
and help will be much appreciated. thanks.
CSV data is text and might require the CharsetEncoder you are using to process the stream before sending it to the C#, but image data is binary and you only want to send a bit-for-bit copy of the data. The problem is likely to be that the stream encoder mistakenly interprets some binary sequences in the image data as text characters that need to be encoded and mangles them.
Just use plain binary stream read and write on both sides (you are already doing it in C#) and confirm that the data is exactly the same. If it isn't, post a hex sample of how it is different.
Finally the solved this issue.
Java(Client)
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ImageServer {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8000);
//code to send image
File file = new File("C:\\Users\\ashish\\Desktop\\image.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
int count=0;
byte[] fileBytes = new byte[(int)file.length()];
int content;
OutputStream outputStream = socket.getOutputStream();
while((content = fileInputStream.read(fileBytes)) != -1){
outputStream.write(fileBytes, 0, (int)file.length());
}
System.out.println("file size is "+ fileBytes.length);
for(byte a : fileBytes){System.out.println(a);}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
C#(Server)
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace Test.SendImageClient
{
public class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = null;
try
{
IPAddress ipadress = IPAddress.Parse("127.0.0.1");
tcpListener = new TcpListener(ipadress, 8000);
/* Start Listeneting at the specified port */
tcpListener.Start();
byte[] bytes = new byte[6790];
byte[] finalBytes;
while(true){
TcpClient client = tcpListener.AcceptTcpClient();
Console.WriteLine("Connected!");
NetworkStream stream = client.GetStream();
int i;
do
{
i = stream.Read(bytes, 0, bytes.Length);
finalBytes = new byte[i];
Console.WriteLine("Size dynamically is "+i);
for (int n = 0; n < i; n++ )
{
finalBytes[n] = bytes[n];
}
}while(stream.DataAvailable);
File.WriteAllBytes("C:\\Users\\ashish\\Desktop\\newImage.jpg", finalBytes);
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
tcpListener.Stop();
}
}
}
}
I have a simple Client-Server Application. The Client selects a file and this file is sending to the server application over network. The server receives this file and writes it into his folder.
The problem is, that i can't open the received files on the server-side until i closed the server-application.
Client
public partial class Form1 : Form {
public string name { get; set; }
public TcpClient clientConnection { get; set; }
public NetworkStream nws { get; set; }
public StreamReader sr { get; set; }
public StreamWriter sw { get; set; }
public int sizeOfConnectedClients { get; set; }
public string clientnamelistString { get; set; }
public Form1() {
InitializeComponent();
connectToServer();
}
private void btnUpload_Click(object sender, EventArgs e) {
OpenFileDialog ofd = new OpenFileDialog();
string filename = null;
string filepath = null;
if (ofd.ShowDialog() == DialogResult.OK) {
filename = System.IO.Path.GetFileName(ofd.FileName);
//tbFilename.Text = System.IO.Path.GetFileName(ofd.FileName);
filepath = ofd.FileName;
//tbFilesize.Text = (new FileInfo(ofd.FileName).Length).ToString() + " KB";
}
Console.WriteLine("filename: " + filename);
var a = File.OpenRead(filepath);
FileInfo fo = new FileInfo(filepath);
long filesize = fo.Length;
Console.WriteLine("Filesize: " + filesize);
// Send filename to server
sw.WriteLine("Filename: " + filename);
sw.Flush();
// Send filesize to server
sw.WriteLine("Filesize: " + filesize);
sw.Flush();
// Write file into fileBytes-Array and sends it in parts
Byte[] fileBytes = new Byte[1024];
long count = filesize;
while (count > 0) {
int recieved = a.Read(fileBytes, 0, fileBytes.Length);
a.Flush();
nws.Write(fileBytes, 0, recieved);
nws.Flush();
count -= recieved;
}
Console.WriteLine("File sends!");
}
public void connectToServer() {
Console.WriteLine("connect to server...");
clientConnection = new TcpClient();
IPAddress ipadress = IPAddress.Parse("127.0.0.1");
clientConnection.Connect(ipadress, 5555);
Console.WriteLine("connected to server!");
nws = clientConnection.GetStream();
sr = new StreamReader(nws);
sw = new StreamWriter(nws);
}
}
Server:
class Server {
private IPAddress ipadress;
private TcpListener serverconnection;
TcpClient clientconnection;
public Server() {
startServer();
waitForClient();
}
public void startServer() {
ipadress = IPAddress.Parse("127.0.0.1");
serverconnection = new TcpListener(ipadress, 5555);
serverconnection.Start();
}
public void waitForClient() {
Console.WriteLine("Server startet. Waiting for incoming client connections...");
clientconnection = serverconnection.AcceptTcpClient();
Console.WriteLine("Client connected with Server!");
recieveFile();
}
public void recieveFile() {
NetworkStream nws = clientconnection.GetStream();
StreamReader sr = new StreamReader(nws);
StreamWriter sw = new StreamWriter(nws);
while (true) {
// Recieve filename
string filename = sr.ReadLine().Remove(0, 10);
// Recieve filesize
long filesize = Convert.ToInt64(sr.ReadLine().Remove(0, 10));
Console.WriteLine("Filename: " + filename);
Console.WriteLine("Filesize: " + filesize);
long count = filesize;
Byte[] fileBytes = new Byte[1024];
var a = File.OpenWrite(filename);
while (count > 0) {
int recieved = nws.Read(fileBytes, 0, fileBytes.Length);
nws.Flush();
a.Write(fileBytes, 0, recieved);
a.Flush();
count -= recieved;
}
a = null;
Console.WriteLine("File was written on HDD. Finish!");
}
}
}
Use the using statement on your readers and writers to ensure everything is disposed from memory properly. example:
using (StreamWriter writer = new StreamWriter(filename))
{
....do stuff
}
I want to create a TcpClient which automatically gets multiple files from server by their name.
I want to get some ideas how I can build such application.
My idea is:
Make a for loop which contains SwitchCase, where I specify my files names. I really don't know if this will work well.
To go out of for loop I can compare the index operator to numbers of files. If they are equal then I go out of for loop.
Example of my idea:
for (int i = 1; i <= 4; i++)
{
switch (----)
{
case 'file1':
code...
break;
case 'file2':
code...
case 'file3':
code...
break;
case 'file4':
code...
break;
default:
code...
break;
}
}
To download a file using ftp you could use the FtpWebRequest and for http use the HttpWebRequest.
Below is a simple example of how to request a file using http (the method is similar for ftp):
public void Download(string url, string localPath)
{
HttpWebRequest request = HttpWebRequest.Create(url);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
FileStream fs = new FileStream(localPath, FileMode.Create);
int count;
byte[] buffer = new byte[8096];
while ((count = stream.Read(buffer, 0, 8096)) > 0)
fs.Write(buffer, 0, count);
fs.Dispose();
response.Close();
}
Instead of using a switch inside a for loop you should iterate an array:
string[] files = new string[]{ url1, url2, ...};
for(int i = 0; i < files.Length; i++)
{
Download(files[i], "file" + i);
}
I solved it like so:
MY app. gets 2 files from server and move files and rename them.
test = mytest
test111 = test2
static string myfile1 = #"C:\inbox\mytest.txt";
static string myfile2 = #"C:\inbox\test2.txt";
//files from server
static string myServerfile = #"C:\Users\me\Documents\file_client\bin\Debug\test.csv";
static string myServerfile1 = #"C:\Users\RH-T3\Documents\file_client\bin\Debug\test111.txt";
public static void Main(string[] args)
{
try
{
for (int i = 0; i < 2; i++)
{
if (i == 0)
{
Console.WriteLine("Downloading test.csv");
string fileName = "test.csv";
Console.WriteLine("Client starts...");
//args[0] = Console.ReadLine();
file_client client = new file_client(args);
Console.WriteLine("efter file_client...");
NetworkStream serverStream = client.clientSocket.GetStream();
LIB.writeTextTCP(serverStream, fileName);
long rest = long.Parse(LIB.readTextTCP(serverStream));
byte[] inStream = new byte[rest];
while (rest != 0)
{
rest = rest - serverStream.Read(inStream, 0, inStream.Length);
Console.WriteLine("REST: " + rest);
}
FileStream fs = new FileStream(fileName, FileMode.Create);
fs.Write(inStream, 0, inStream.Length);
{
fs.Close();
serverStream.Close();
}
if (File.Exists(myfile1))
{
File.Delete(myfile1);
}
File.Move(myServerfile, myfile1);
Console.WriteLine("Moved");
System.Threading.Thread.Sleep(500);
}
else
{
Console.WriteLine("Downloading .txt file");
string fileName = "test111.txt";
Console.WriteLine("Client starts...");
//args[0] = Console.ReadLine();
file_client client = new file_client(args);
Console.WriteLine("efter file_client...");
NetworkStream serverStream = client.clientSocket.GetStream();
LIB.writeTextTCP(serverStream, fileName);
long rest = long.Parse(LIB.readTextTCP(serverStream));
byte[] inStream = new byte[rest];
while (rest != 0)
{
rest = rest - serverStream.Read(inStream, 0, inStream.Length);
Console.WriteLine("REST: " + rest);
}
FileStream fs = new FileStream(fileName, FileMode.Create);
fs.Write(inStream, 0, inStream.Length);
{
fs.Close();
serverStream.Close();
}
if (File.Exists(myfile2))
{
File.Delete(myfile2);
}
File.Move(myServerfile1, myfile2);
Console.WriteLine("Moved");
System.Threading.Thread.Sleep(500);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Cannot be DONE!");
}