Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7929279
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T20:01:12+00:00 2026-06-03T20:01:12+00:00

i have this code server part: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data;

  • 0

i have this code
server part:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Diagnostics;
namespace server
{
    public partial class server : Form
    {
        public  byte[] data;

        public  byte[] data1;
        public static Socket sock ;
        public static List<Socket> sock_li = new List<Socket>();
        public delegate void operation(string s);
        public delegate void operation2();
        public delegate bool verifier();
        public static int nombre = 0;

        public server()
        {
            InitializeComponent();
          this.Show();
          data1 = new byte[1024];
          data = new byte[1024];
          comboBox1.Items.Add(0);
         sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
              IPAddress adress = IPAddress.Parse("127.0.0.1");
              IPEndPoint iep = new IPEndPoint(adress, 4000);
              EndPoint ep = (EndPoint)iep;
              sock.Bind(iep);
              sock.Listen(1000);
               sock_li.Add(sock.Accept());

               if (this.InvokeRequired) Invoke((operation)effectuer4, "le client " + 0 + " a rejoint le chat");
               else effectuer4("le client " + 0 + " a rejoint le chat");
               Thread li = new Thread(liste);
               li.Start();

               Thread ko = new Thread(new ParameterizedThreadStart(listenning));
               ko.Start(0);
          }
        public void liste() {
            nombre = 1;
        while (true)
              {
                  sock_li.Add(sock.Accept());
                  if (this.InvokeRequired) Invoke((operation)effectuer4, "le client " + nombre.ToString() + " a rejoint le chat");
                  else effectuer4("le client " + nombre.ToString() + " a rejoint le chat");
                  if (this.InvokeRequired) Invoke((operation)effectuer5,  nombre.ToString() );
                  else effectuer5( nombre.ToString() );
                  Thread ko = new Thread(new ParameterizedThreadStart(listenning));
                  ko.Start(nombre);
                  nombre++;
              }




        }

        private void effectuer5(string p)
        {
            comboBox1.Items.Add(p);
        }
        public void listenning(Object j)
        {

            int i = (int)j;

            String s="";
            while (true)
            {
                if (sock_li[i].Receive(data) > 0)
                {
                 s = ASCIIEncoding.ASCII.GetString(data);

                              if (this.InvokeRequired) Invoke((operation)effectuer4, "client " + i.ToString() + " : " + s);
                              else effectuer4("client " + i.ToString() + " : " + s);


                }

            }
        }
        private void effectuer(String s)
        {
            textBox1.Text += "serveur:  " + s + "\r\n";
              message.Text  = "";
        }
        private void effectuer4(String s)
        {
            textBox1.Text +=  s + "\r\n"; message.Text = "";

        }

      private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            sock.Close();
            Application.Exit();
             }
    private void buttonSend_Click(object sender, EventArgs e)
        {
           String s = message.Text ;
           data1.Initialize();
            data1 = System.Text.Encoding.ASCII.GetBytes(s);


            int i = int.Parse(comboBox1.SelectedItem.ToString());
            sock_li[i].Send(data1);

       if (InvokeRequired) Invoke((operation)effectuer, s); else effectuer(s);

           }
        }
     }

and the part client is:

 using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Timers;
    using System.Threading;
    using TrackingUnitSimulator;
    using NHibernate;
    using System.Xml;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Diagnostics;
    using base_donnee;

    namespace GUInterface
    {
        public partial class TrackingUnitClientForm : Form
        {
            #region variables
            public string fich_log = "";
            public Socket sock;
            public IPEndPoint ipEnd = null;
            public static bool connexion = false;
            private static byte[] data;
            public static byte[] data1;
            public  string serial;
            public string[] types= new string[6]{  "EasyTrace"," WatchTrace","MultiTrace","PocketTrace","TrailerTrace","SmartTrace"};
            public static string[] typ = new string[100];
            public static string[] validite = new string[100];
            public static float[] longi = new float[100];
            public static float[] lati = new float[100];
           public static float[] scenarios = new float[100];
            public static int nombre = 0;
           public static TCPClient tcpClient = null;
           public static int[] tab = new int[6];
           public static int debut = 0;
           public static int fin = 0;
           public static string s;
           public int atte = 0;

            public static scenario sc = null;
            #endregion
           #region delegates
           delegate void CommandReceivedCallBack(TCPClient tcpClient, string commandText);
           delegate void faire(string s);
           delegate void faire2(string s1, string s2);
           delegate void masquer(int i);
           delegate void received(string i);
           #endregion


            public void received1(string i)
            {
                receivedCommand.Text += "  New command: " + i + "\r\n";
            }

            #endregion

            public TrackingUnitClientForm(string b, bool ver, string fichier_log, string fichier_scenario)
            {
                InitializeComponent();
                fich_log = fichier_log;
                Disconnexionbt.Hide();
                sc = new scenario(@fichier_scenario);
                serial = b;
                int p = 0;
                Random m = new Random();
                p = m.Next(0, 5);
                if (ver == true)
                {
                    equipment cr = new equipment();
                    cr.enregistrer(b, types[p]);
                }
                label4.Text = types[p];
                label2.Text = serial;

                if (fich_log != "")
                {

                    if (InvokeRequired) Invoke((faire)log, DateTime.Now.ToString() + " | " + "L'équipment num" + serial.ToString() + " se connecte\r\n");
                    else log(DateTime.Now.ToString() + " | " + "L'équipment num" + serial.ToString() + " se connecte\r\n");
                }
                connecter();


                  Thread th = new Thread(listening);
                th.Start();


            }

            public void connecter() {
                try
                {
                    IPAddress adress = IPAddress.Parse("127.0.0.1");
                    ipEnd = new IPEndPoint(adress, 4000);
                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sock.Connect(ipEnd);
                    this.Connexionbt.Hide();
                    this.Disconnexionbt.Show();
                    lblConnectionStatus.Text = "Online";
                    lblConnectionStatus.ForeColor = Color.Blue;

                }
                catch (Exception exc)
                {

                    if (InvokeRequired) Invoke((masquer)masquer1, 4);
                    else
                        this.Disconnexionbt.Hide();
                    lblConnectionStatus.Text = "Offline";
                    lblConnectionStatus.ForeColor = Color.Red;
                    MessageBox.Show(exc.Message, Text);
                }
                }
            public void listening() {
                String s = null;
               try
                {
                repeter:

                    data = new byte[1024];
                s = ASCIIEncoding.ASCII.GetString(data);
                    if (sock.Receive(data) > 0 && s!="")
                    {


                        if (String.Compare(s, "$$Y01") == 0)
                        {
                            if (InvokeRequired) Invoke((received)received1, "Actual Postion Request"); else received1("Actual Postion Request");
                        }
                        else if (String.Compare(s, "$$Y03") == 0)
                        {
                            if (InvokeRequired) Invoke((received)received1, "Stop The Vehicle"); else received1("Stop The Vehicle");
                        }
                        else if (String.Compare(s, "$$Y06") == 0)
                        {
                            if (InvokeRequired) Invoke((received)received1, "Cancel The Stop"); else received1("Cancel The Stop");
                        }
                        else
                        {
                            if (InvokeRequired) Invoke((received)received1, s); else receivedCommand.Text += s + "\r\n";
                        }

                    }
                    data = new byte[0];
                    goto repeter;

                }
                catch { }
            }



        }
    }

but i have this problem : when i execute more than 2 clients some messages will be empty especially the first ( the buffer data is empty!!) how can i resolve this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T20:01:13+00:00Added an answer on June 3, 2026 at 8:01 pm
     data = new byte[1024];
     s = ASCIIEncoding.ASCII.GetString(data);
     if (sock.Receive(data) > 0 && s!="")
     {
    

    k… this allocates a new buffer (all zeros), decodes this all-zero buffer to get a string (s), then actually asks for data (disregarding any kind of “framing”), doesn’t bother decoding the data received, and then compares s (which we know came from all-zeros) to a number of expected strings of which we already know it is none.

    So yes, the first “receive” will always miss your switch, simply because you aren’t decoding correctly. However! You MUST NOT assume that each “receive” is going to get the data from a single “send”. TCP here is just a stream. You are going to get “some data”, which might be:

    • exactly one message, if you are really lucky
    • part of a message
    • 27 small messages
    • the end of one message, and entire second message, and the start (incomplete) of a third

    this is why you need to use “framing” to detect sub-messages on a stream, for example looking for newline characters in a text-based protocol, or using length-prefix data in a binary protocol.

    Since this is ASCII, you don’t have to worry about partial characters, but you still need to hold on to the result of Receive, so that you know how many bytes to look at inside data (i.e. if you only get 27 bytes from the socket, you should only decode 27 bytes).

    You might find this useful for understanding this further.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code to create a webapp in my server: import web urls
I used to have this code working with my Tomcat server: HttpRequestBase targetRequest =
I have this mySQL code that connects to my server. It connects just fine:
I have this horribly stripped delphi code that basically login to server, save cookie
This is my server code I have a problem because my program freeze and
I have this code to show a map using the Virtual Earth API: <script
I have this piece of code using standard sockets: void set_fds(int sock1, int sock2,
I'm using this code to replicate Data Driven Subscriptions in MSSQL 2008. http://sqlblog.com/blogs/greg_low/archive/2008/08/13/data-driven-subscriptions-in-sql-server-2005-standard-edition.aspx As
I have this code to download a file, but on sourceforge.net sever there is
I have this php code $jsonArray = array(); $sql = SELECT ID,CLIENT FROM PLD_SERVERS;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.