473,406 Members | 2,273 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

how to write a file faster

375 256MB
Hi All ,

I have with me a server socket program, I am receiving all the clients, but what happens is i have to write it into a file.
This consumes time.

So we do not have a data loss, but as the time taken to write into the log file increases, some of the data does not get written.

This is the code

//ONLY SHOBA
Expand|Select|Wrap|Line Numbers
  1. #define debug
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Drawing;
  8. using System.Text;
  9. using System.Net;
  10. using GeoBoundary;
  11. using LLUTMConvert;
  12. using System.Collections.Specialized;
  13. using System.IO;
  14. using System.Globalization;
  15. using System.Net.Sockets;
  16. using System.Collections;
  17. using System.Threading;
  18. using System.Configuration;
  19. using System.Messaging;
  20. using AmiComServerConsole;
  21. using Microsoft.VisualBasic;
  22. using Microsoft.VisualBasic.CompilerServices;
  23. using System.Runtime.CompilerServices;
  24. using System.Windows.Forms;
  25. namespace SocketServer
  26. {
  27.  
  28.     public sealed class SingletonExample
  29.     {
  30.         private static SingletonExample instance = null;
  31.         private static readonly object objectlockCheck = new object();
  32.  
  33.         private SingletonExample()
  34.         {
  35.         }
  36.  
  37.         public static SingletonExample Instance
  38.         {
  39.             get
  40.             {
  41.                 lock (objectlockCheck)
  42.                 {
  43.                     if (instance == null)
  44.                         instance = new SingletonExample();
  45.                     return instance;
  46.                 }
  47.             }
  48.  
  49.  
  50.  
  51.         }
  52.         public void WriteLogMessage(string strMessage)
  53.         {
  54.             try
  55.             {
  56.  
  57.                 string text4 = "D:\\COMSERVER\\9.7\\dummysobha\\bin\\Debug\\Log \\Log_first_8.11.2008.txt";
  58.                 StreamWriter writer1 = File.AppendText(text4);
  59.                 writer1.WriteLine(DateTime.Now.ToString() + " " + strMessage);
  60.                 writer1.Close();
  61.             }
  62.             catch (Exception)
  63.             {
  64.             }
  65.         }
  66.     }
  67.  
  68.     public class StateObject  //class created by mahesh to clear the duplicate records
  69.     {
  70.         // Client socket.
  71.         public Socket workSocket = null;
  72.         // Size of receive buffer.
  73.         public const int BufferSize = 5000;
  74.         // Receive buffer.
  75.         public byte[] buffer = new byte[BufferSize];
  76.         // Received data string.
  77.         public string sb;
  78.  
  79.     }
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.     class Program
  87.     {
  88.  
  89.  
  90.         private string DatabaseType;
  91.  
  92.  
  93.         public static int i=0;
  94.         public string strConOra;
  95.         public string strConSql;
  96.  
  97.         public AsyncCallback pfnWorkerCallBack;
  98.         private Socket m_mainSocket;
  99.  
  100.         public int port = 7777;
  101.         public byte[] m_byBuff = new byte[5000];
  102.         public int flag2 = 0;
  103.         public string queuePath;
  104.         private string strDateFormat;
  105.         private string strLocation;
  106.  
  107.         public byte[] inValue = new byte[] { 1, 0, 0, 0, 0, 0, 5, 0, 1, 0, 0, 0 }; //1 -Minutes // 0,5 --   0 --seconds  6th parameter-->seconds 7th parameter-->minutes
  108.  
  109.         public byte[] outvalue = new byte[10];
  110.  
  111.         private string m_strConnection;
  112.         private SqlConnection ocon;
  113.         private SqlConnection ocon2;
  114.  
  115.         public long Mylockcounter = 0;
  116.  
  117.         private SqlConnection MyCon;
  118.         public string Conn;
  119.         public Program()
  120.         {
  121. #if debug
  122.             this.queuePath = ".\\private$\\AMI";
  123. #else
  124.             this.queuePath = ".\\private$\\AMI";
  125. #endif
  126.             this.m_strConnection = ConfigurationSettings.AppSettings["Connection"];
  127.             this.strDateFormat = null;
  128.             this.strLocation = null;
  129.             StartListen();
  130.  
  131.  
  132.         }
  133.         public void StartListen()
  134.         {
  135.  
  136.  
  137.             try
  138.             {
  139.                 NameValueCollection collection1 = ConfigurationSettings.AppSettings;
  140.                 //string portStr = this.IPPort;
  141.                 //int port = System.Convert.ToInt32(portStr);
  142.                 // Create the listening socket...
  143.                 m_mainSocket = new Socket(AddressFamily.InterNetwork,
  144.                                           SocketType.Stream,
  145.                                           ProtocolType.Tcp);
  146.                 IPAddress ip;
  147.  
  148. #if debug
  149.                 string ipstr = "192.168.0.20";
  150. #else
  151.                 string ipstr = "192.168.3.7";
  152. #endif
  153.  
  154.                 ip = IPAddress.Parse(ipstr);
  155.  
  156.                 IPEndPoint ipLocal = new IPEndPoint(ip, port);
  157.                 //// Bind to local IP Address...
  158.                 m_mainSocket.Bind(ipLocal);
  159.                 //// Start listening...
  160.                 m_mainSocket.Listen(400);
  161.  
  162.  
  163.  
  164.                 // New method
  165.  
  166.                 string text5 = "provider=OraOLEDB.Oracle.1;Persist Security Info=False;User ID=VTS;password=VTS;Data Source=DMGIS";
  167.                 string text4 = "workstation id=192.168.0.20;Data Source=192.168.0.20;User ID=sa;Password=1234;Initial Catalog=VTS1;Max Pool Size=300;Min Pool Size=1;Pooling=True";
  168.                 this.Conn = "workstation id=192.168.0.20;Data Source=192.168.0.20;User ID=sa;Password=1234;Initial Catalog=VTS1;Max Pool Size=300;Min Pool Size=1;Pooling=True";
  169.  
  170.                 MyCon = new SqlConnection(this.Conn);
  171.                 MyCon.Open();
  172.  
  173.  
  174.                 this.DatabaseType = "SQL";
  175.                 this.strDateFormat = "us";
  176.                 if (this.strLocation == null)
  177.                 {
  178.                     this.strLocation = "Road name not available";
  179.                 }
  180.                 if (this.DatabaseType == "SQL")
  181.                 {
  182.                     this.strConSql = text4;
  183.                 }
  184.                 else if (this.DatabaseType == "ORACLE")
  185.                 {
  186.                     this.strConOra = text5;
  187.                 }
  188.                 else
  189.                 {
  190.                     WriteErrorLogMessage("Proper database was not mentioned");
  191.                 }
  192.                 collection1 = null;
  193.  
  194.              while (true)
  195.                 {
  196.  
  197.                     m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  198.                     Thread.Sleep(2000);
  199.                 }
  200.  
  201.             }
  202.             catch (Exception e1)
  203.             {
  204.             }
  205.         }
  206.  
  207.  
  208.         public void OnClientConnect(IAsyncResult asyn)
  209.         {
  210.             try
  211.             {
  212.                 Socket msocket;
  213.  
  214.                 msocket = m_mainSocket.EndAccept(asyn);
  215.  
  216.                 msocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1);
  217.                 msocket.IOControl(IOControlCode.KeepAliveValues, inValue, outvalue); 
  218.                 WaitForData(msocket);
  219.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  220.  
  221.             }
  222.  
  223.             catch (Exception e1)
  224.             {
  225.                // WriteErrorLogMessage(e1.Message);
  226.             }
  227.         }
  228.  
  229.        public void WaitForData(System.Net.Sockets.Socket soc)
  230.         {
  231.             try
  232.             {
  233.                 Console.WriteLine("\n");
  234.                 Console.WriteLine("WaitforData");
  235.                 Console.WriteLine("\n");
  236.  
  237.                 if (pfnWorkerCallBack == null)
  238.                 {
  239.  
  240.                     pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
  241.                 }
  242.  
  243.                StateObject state = new StateObject();
  244.                 state.workSocket = soc;
  245.  
  246.                 soc.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, pfnWorkerCallBack, state);
  247.  
  248.  
  249.             }
  250.             catch (Exception e1)
  251.             {
  252.             }
  253.  
  254.         }
  255.         public void OnDataReceived(IAsyncResult asyn)
  256.         {
  257.               MyCon = new SqlConnection(this.Conn);
  258.  
  259.             try
  260.             {
  261.                 Console.WriteLine("\n");
  262.                 Console.WriteLine("OnDataRecd");
  263.                 Console.WriteLine("\n");
  264.  
  265.                 StateObject stateobject = (StateObject)asyn.AsyncState;
  266.                 Socket sock = stateobject.workSocket;
  267.  
  268.                 //assgning the app socket to new socket
  269.                Object thisLock = new Object();
  270.  
  271.                 string previousString;
  272.                 int nBytesRec = sock.EndReceive(asyn);
  273.                 if (nBytesRec > 0)
  274.                 {
  275.                     string sReceived = System.Text.Encoding.ASCII.GetString(stateobject.buffer, 0, StateObject.BufferSize);
  276.                     sReceived = sReceived.TrimEnd('\0');
  277.                     if (sReceived != null && sReceived != " " && sReceived != "")
  278.                     {
  279.                         {
  280.  
  281.                             {
  282.                   WriteLogMessage(sReceived);
  283.                         byte[] Buffer = new byte[StateObject.BufferSize];
  284.                         stateobject.buffer = Buffer;
  285.                         sock.BeginReceive(stateobject.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(OnDataReceived), stateobject);            }
  286.  
  287.                 }
  288.                 else
  289.                 {
  290.                     sock.Disconnect(false);
  291.                     sock.Close();
  292.                     stateobject = null;
  293.                sole.WriteLine("Inside the Else part in ondatareceived");
  294.                                     }
  295.  
  296.             }
  297.  
  298.             catch (SocketException e1)
  299.             {
  300.  
  301.                Console.WriteLine("Inside the catch1 part in ondatareceived");
  302.             }
  303.  
  304.            catch (Exception e1)
  305.             {
  306.            Console.WriteLine("Inside the Catch2 part in ondatareceived");
  307.             }
  308.         }
  309.  

Any help will be appreciated.

Regards
cmrhema
Aug 12 '08 #1
2 1664
Plater
7,872 Expert 4TB
I've not had trouble with any data loss when logging at high speeds.
I DO however see that you are not doing anything in the catch section of the try/catch for your logging. I would guess errors are being thrown.
I would also guess that sine you use async connections, that multiple connections are attempting to log at once and it is throwing exceptions. Try putting some code in to check for exceptions in your writelog function. I bet you will get a better idea of what is happening.
Aug 12 '08 #2
cmrhema
375 256MB
I've not had trouble with any data loss when logging at high speeds.
I DO however see that you are not doing anything in the catch section of the try/catch for your logging. I would guess errors are being thrown.
I would also guess that sine you use async connections, that multiple connections are attempting to log at once and it is throwing exceptions. Try putting some code in to check for exceptions in your writelog function. I bet you will get a better idea of what is happening.
We have done it, but we did another thing too, instead of writing in a log file, we write into a queue,
It writes up everything without any data loss.
But when we write up in a log file we face data loss.

As of now we decided to put up in a queue first and then read the data from it.

Any suggestions other than that.

Many thanks for the reply Plater.

Regards
cmrhema
Aug 13 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Tony C | last post by:
Does Python have a function that is analogous to C's write() or fwrite()- that is , I want to write a file (of arbitrary data) that is 100K, or 1MB (or more) bytes long.. Both write() and...
4
by: Jon Hyland | last post by:
Hi all, I'm looking for the fastest way to write (and/or read) binary to a file in VC++. I've been using the fstream object in this way: //unsigned char *pDataOut and long iLength initilized...
12
by: Christian Blackburn | last post by:
Hi Gang, I would like to know how to write a single bit to a file (if that's possible). I would like to repetitiously write a 1 or 0 as the data I'm trying to save would dictate. Thanks in...
1
by: tim | last post by:
I have a multi-dimensional byte array, private someArray(,,) as byte and it's huge redim someArray(100,640,480,3) after populating the array, I write it to a text file to save it. (so I don't...
5
by: Eric Cadwell | last post by:
Is there a faster way to write the last 100K of a large file? This code takes almost two minutes to run on my machine. int buffer = 100000; int length = 2000000000; string file =...
12
by: Sean Davis | last post by:
I am working on a simple script to read from one database (oracle) and write to another (postgresql). I retrieve the data from oracle in chunks and drop the data to postgresql continuously. The...
3
by: golden | last post by:
Hello, I am going to ask a question regarding write and lseek. I will provide code at the end of this, but first some background. I am trying to identify the cause of some latency in...
23
by: LilacSkin | last post by:
Hi, Currently, I write an signed long long in a file with the fprintf function: signed long long * pData = NULL; unsigned long long k = 0; unsigned long DataAvail = 0 ; pDataRx = (signed...
0
by: cmrhema | last post by:
Hi, We are receiving huge number of data thro sockets, which we write up in a Message Queue. Thereafter we take all the values from the Queue and write up into the database. However we notice...
1
by: Mohamed Yousef | last post by:
Hello , let's say , I'm moving large files through network between devices what is the fastest way to do this ? what i came up with :- 1) using regular file operations with an in memory limit...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.