Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data multiple times over a single socket

Server side code:

static void Main(string[] args)
        {
            static Socket sck;
            Console.WriteLine("Server Started...");
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sck.Bind(new IPEndPoint(0, 1234));
            while (true)
            {
                sck.Listen(100);
                Socket accepted = sck.Accept();
                buffer = new byte[accepted.SendBufferSize];
                int bytesRead = accepted.Receive(buffer);
                byte[] formatted = new byte[bytesRead];
                for (int i = 0; i < bytesRead; i++)
                    formatted[i] = buffer[i];
                string strdata = Encoding.ASCII.GetString(formatted);
                Console.WriteLine(strdata + "\r");
            //    sck.Close();
            }

Client side code:

static void Main(string[] args)
        {
            static Socket sck;
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
            try
            {
                sck.Connect(localEndpt);
            }
            catch
            {
                Console.Write("Unable to Connect");
            }
            while (true)
            {
                Console.WriteLine("Enter Text");
                string sendtext = Console.ReadLine();
                byte[] Data = Encoding.ASCII.GetBytes(sendtext);
                sck.Send(Data);
                Console.WriteLine("Data Sent!");
                //sck.Close();
                //Console.Read();
            }

I want to send text from the Client side multiple times, however the text is sent only the first time. Please tell me where am i going wrong.

like image 909
Tempo Avatar asked Jun 15 '26 10:06

Tempo


1 Answers

The problem is on your server. You are in a loop listening for a new connection, accepting it and receiving data. Yet what happens is the listening statement see's a client who wants to connect. Your accept statement actually connects the client and your receive statement receieves the first data. After that your server starts listening for a new connection again but is not receiving more data from the already existing connection. You should build a loop around the Accept statement and a loop around the Receive statement on your server to fix this problem

like image 98
Polity Avatar answered Jun 17 '26 22:06

Polity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!