Click here to Skip to main content
15,886,693 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
Hello,
I have created a TCP client server application in c# visual studio 2005 to broadcast a randomly generated float value in server and send to client. client requires to give the username and password to recieve the value. It works fine for one client but if another client is added the program fails.
can you please help me with this.

Thank you
Arpan

Server code:
C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace server
{
    public class login
    {
        Socket s;

        public login(Socket valueS)
        {
            s = valueS;
        }

        public void check()
        {
            try
            {

                byte[] uname = new byte[100];
                byte[] pword = new byte[100];
                int sizeuser = s.Receive(uname);
                int sizepword = s.Receive(pword);

                if (sizeuser > 0 && sizepword > 0)
                {
                    Console.WriteLine("Recieved");
                    TextReader objTxtReader = new StreamReader("login.txt");
                    String username = objTxtReader.ReadLine();
                    String password = objTxtReader.ReadLine();
                    String test = ASCIIEncoding.ASCII.GetString(uname);
                    test = test.Substring(0, sizeuser);
                    if (username == (ASCIIEncoding.ASCII.GetString(uname)).Substring(0, sizeuser) && password == (ASCIIEncoding.ASCII.GetString(pword)).Substring(0, sizepword))
                    {

                    }
                    else
                    {
                        ASCIIEncoding asen2 = new ASCIIEncoding();
                        s.Send(asen2.GetBytes("0"));
                    }

                }

            }
        catch(Exception e){  }

        }

    }


    public  class Program
    {
      
        static void Main(string[] args)
        {
            try
            {
                IPAddress ipAd = IPAddress.Parse("192.168.10.68");
                TcpListener myList = new TcpListener(ipAd, 8002);
                myList.Start();
                Random randDouble = new Random();
                double randValue;
                Socket s = myList.AcceptSocket();
                login objLogin = new login(s);
                Thread thdLogin = new Thread(new ThreadStart(objLogin.check));
                thdLogin.Start();
                thdLogin.Join();
                while (true)
                {
                randValue = randDouble.NextDouble();
                Console.WriteLine(randValue);
                Thread.Sleep(500);
                ASCIIEncoding asen = new ASCIIEncoding();
                String strRandValue = randValue.ToString();
                byte[] msg = asen.GetBytes(strRandValue);
                s.Send(msg);
                }
                s.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
    }
}



Client Code:

C#
using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                Console.WriteLine("Connecting.....");
                String username=null;
                String password= null;

                tcpclnt.Connect("192.168.10.68", 8002);
                Console.WriteLine("Connected");
                Console.WriteLine("Enter Username");
                username =  Console.ReadLine();
                Console.WriteLine("Enter Password");
               // password =  Console.ReadLine();
                ConsoleKeyInfo key;
                do
                {
                    key = Console.ReadKey(true);
                    if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                    {
                        password += key.KeyChar;
                        Console.Write("*");
                    }
                    else
                    {
                        if (key.Key == ConsoleKey.Backspace && password.Length > 0)
                        {
                            password = password.Substring(0, (password.Length - 1));
                            Console.Write("\b \b");
                        }
                    }
                }while(key.Key!=ConsoleKey.Enter);

                Console.Write("\n");
                Stream stm = tcpclnt.GetStream();
                ASCIIEncoding uname = new ASCIIEncoding();
                byte[] byteUsername = uname.GetBytes(username);
                ASCIIEncoding pword = new ASCIIEncoding();
                byte[] bytePword = uname.GetBytes(password);
                stm.Write(byteUsername, 0, byteUsername.Length);
                stm.Write(bytePword, 0, bytePword.Length);

                byte[] byteMsg = new byte[100];
                int length = stm.Read(byteMsg, 0, 100);
                while (length>1)
                {
                    for (int i = 0; i < length; i++)
                    Console.Write(Convert.ToChar(byteMsg[i]));
                    Console.WriteLine("\n");
                    length = stm.Read(byteMsg, 0, 100);
                }  
                 
                if (length == 1)
                {
                    Console.WriteLine("Invalid username or password");
                }
                tcpclnt.Close();
                String str1 = Console.ReadLine();
            }

            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
    }
}
Posted

If you want to accept multiple connections then you should have code kind of ...

C#
while( true )
{
SOCKET soc = AcceptSocket ()

Create a thread and send the soc object to that thread. 
}


Moral of the story is ,

Your server should accept the connection and should delegate the work associated with the connection to thread.
You main program should be free and wait for the connection.

In your case , you are calling AcceptSocket just once. This is why you are getting able to connect it first time.
Second time , as there is no one at server side is waiting for connection, it is failing.
 
Share this answer
 
Comments
amsainju 8-Oct-12 7:35am    
how can i check if there is a client request ?
PrafullaVedante 8-Oct-12 7:37am    
AcceptSocket is a blocking call. Your execution will be blocked until you receive any request from client.
amsainju 8-Oct-12 7:55am    
thank you for your help I will try to solve the problem
 
Share this answer
 
Comments
amsainju 9-Oct-12 5:11am    
Thank you for your help
ridoy 9-Oct-12 5:59am    
always welcome

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