Click here to Skip to main content
15,888,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanted to create apps like this:

User select dates in client up.
When he clicks send button client sends dates over TCP to server.
When server receives dates he process them and retuns to client csv in string.
When client receives he writes data to file.

Heres my code:

Servers part:

C#
private void StartListen()
{
    server.Start(); // Starts Listening to Any IPAddress trying to connect to the program with port 1980
    new Thread(() => // Creates a New Thread (like a timer)
    {
        client = server.AcceptTcpClient(); //Waits for the Client To Connect
        zapisiLog("klient se spojio");
        if(client.Connected) // If you are connected
        {
            ServerReceive(); //Start Receiving
        }
    }).Start();
}
public void ServerReceive()
{
    stream = client.GetStream(); //Gets The Stream of The Connection
    new Thread(() => // Thread (like Timer)
    {
        while((i = stream.Read(datalength, 0, 4)) != 0)//Keeps Trying to Receive the Size of the Message or Data
        {
            byte[] data = new byte[BitConverter.ToInt32(datalength, 0)]; // Creates a Byte for the data to be Received On
            stream.Read(data, 0, data.Length); //Receives The Real Data not the Size
            this.Invoke((MethodInvoker) delegate // To Write the Received data
            {
                String s = Encoding.Default.GetString(data); // Converts Bytes Received to String
                string[] datumi = s.Split('_');
                sd1 = datumi[0];
                sd2 = datumi[1];
                mstat = datumi[2];
//this is a funtion that coonects to database and return tables
                DataSet dset = prikupi_podatke();

                if(datumi[2] != "" & dset != null)
                {
                    String zs = obradi(ref dset);
                    if(zs != "")
                    {
                        ServerSend(zs);
                    }
                    else
                    {
                        zapisiLog("Obrada podataka nije uspjela");
                    }
                }
                else
                {
                    zapisiLog("Prikupljanje podataka nije uspjelo");
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\codexExcel.log");
                    try
                    {

                        sw.WriteLine(DateTime.Now.ToString() + ";Prikupljanje podataka nije uspjelo");
                        sw.Close();
                    }
                    catch(Exception)
                    {
                        sw.Close();
                    }
                }
            });
        }
    }).Start(); // Start the Thread
}


Clients part:
C#
public void spoji()
{
    try
    {
        client = new TcpClient(ip, 1980); //Trys to Connect
        ClientReceive(); //Starts Receiving When Connected
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message); // Error handler :D
    }
}
public void ClientSend(string msg)
{
    stream = client.GetStream(); //Gets The Stream of The Connection
    byte[] data; // creates a new byte without mentioning the size of it cuz its a byte used for sending
    data = Encoding.Default.GetBytes(msg); // put the msg in the byte ( it automaticly uses the size of the msg )
    int length = data.Length; // Gets the length of the byte data
    byte[] datalength = new byte[4]; // Creates a new byte with length of 4
    datalength = BitConverter.GetBytes(length); //put the length in a byte to send it
    stream.Write(datalength, 0, 4); // sends the data's length
    stream.Write(data, 0, data.Length); //Sends the real data
}
public void ClientReceive()
{
    string primljeno;
    stream = client.GetStream(); //Gets The Stream of The Connection
    new Thread(() => // Thread (like Timer)
    {
        while((i = stream.Read(datalength, 0, 4)) != 0)//Keeps Trying to Receive the Size of the Message or Data
        {
            // how to make a byte E.X byte[] examlpe = new byte[the size of the byte here] , i used BitConverter.ToInt32(datalength,0) cuz i received the length of the data in byte called datalength :D
            byte[] data = new byte[BitConverter.ToInt32(datalength, 0)]; // Creates a Byte for the data to be Received On
            stream.Read(data, 0, data.Length); //Receives The Real Data not the Size
            this.Invoke((MethodInvoker) delegate // To Write the Received data
            {
                primljeno = Encoding.UTF8.GetString(data); // Encoding.Default.GetString(data); Converts Bytes Received to String
                if(primljeno != "")
                {
                    //klijent pbrađuje
                    //obradi(ref primljeno);
                    //server obrađuje
                    obradi2(ref primljeno);
                }
                else
                {
                    MessageBox.Show("Komunikacija nije uspjela");
                }

            });
        }
    }).Start(); // Start the Thread
}

Applications are working well when server and host are on same machine. But not stable on different machines. By not working well I mean app crash with "server is not responding". What am i doing wrong?
Posted

1 solution

I would not recommend using threads the way you are using them in your code, instead take a look at these examples on MSDN:

Asynchronous Client Socket Example[^]
Asynchronous Server Socket Example[^]

I have based some applications running on different machines on these examples and haven't had any serious issues.
I have to add that I have been using this concept on an internal network where the server took care of maybe 10-15 clients at a time and the request load was pretty low.
 
Share this answer
 
v2
Comments
Afzaal Ahmad Zeeshan 10-Oct-15 4:01am    
5ed.
George Jonsson 10-Oct-15 4:51am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900