Click here to Skip to main content
15,885,711 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i create client server program using c#
client program is form application and server is console application.

in client i had 4 forms, when i send data from first form , server can receive it, but when i send from another form , server can not receive the data.
any one know why??

look : in client side i used windows application form,

first form it takes user name and password and send it to server.

then server check if this user is available and send availability to
client,

then client open another form and close the first form

and ask for some details like tel,mob and etc,(until here i don't have
any problem)

then it should send details to server,

but it seems the server dosen't accept the data from another form, it seems it connect only to first form.

the code for form1 is :

C#
TcpClient c = new TcpClient("127.0.0.1", 1000);
NetworkStream ns = c.GetStream();
string st1 = textBox1.Text;
string st2 = textBox2.Text;
string name = string.Concat("F" + len + len2 + len3 + st1 + passhash + st3);
byte[] buf = System.Text.Encoding.ASCII.GetBytes(name);  // convert string to an array of bytes
ns.Write(buf, 0, name.Length);  // write to stream



this work for first form,but when i use this code for another form it doesn't work, i don't no why?

now i know the problem but i don't know how to solve this
it seems each form needs specific port number.
in this case i can not assign to each form a port, because it had many form, in other hand in server side i should listen to many port.

i tried to make child form, but it also doesn't work, and it's not inherit tcpclient.

so, what would the solution be ?

this is server code :

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AWMOdel;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener l = new TcpListener(IPAddress.Any, 1000);

            l.Start();
            Console.WriteLine("Server has started.Waiting for clients...");
            TcpClient c = l.AcceptTcpClient();
            Console.WriteLine(" >> Accept Connection From Clinet ");
            NetworkStream ns = c.GetStream();

           while(true)
           {
               byte[] buf = new byte[200];
                ns.Read(buf, 0, 200);
                string st = System.Text.Encoding.ASCII.GetString(buf);
                Console.WriteLine(st);


                //devide the string
                int le = st[1];
                int le2 = st[2];
                int le3 = st[3];
                string flag = st.Substring(0, 1);

                string name;
                string pass;
                string position;
                name = st.Substring(4, le);
                pass = st.Substring(4 + le, le2);
                position = st.Substring(4 + le + le2, le3);
                
                Console.WriteLine(name);
                
               //finish divede string

               byte[] buf2;
                if (string.Compare(name, "Administrator")==0)
                {
                    string one = Convert.ToString(1);
                    buf2 = System.Text.Encoding.ASCII.GetBytes(Convert.ToString(one));
                    ns.Write(buf2, 0, one.Length);
                }
              
                NetworkStream ns2 = c.GetStream();
                byte[] stin = new byte[200];
                ns.Read(stin, 0, 100);
                string stinfo = System.Text.Encoding.ASCII.GetString(stin);
                Console.WriteLine(stinfo);
                

            }//end while true



        }//end of main
       
    }//end of class program
}//end of namespace



this is client code :
form 1 :

C#
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.Net;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace newform1
{
    

    public partial class Form1 : Form
    {

    

        TcpClient c = new TcpClient("127.0.0.1", 1000);

        public Form1()
        {
            InitializeComponent();
            textBox2.PasswordChar = '*';
        }

        private void Form1_Load(object sender, EventArgs e)
        {
             NetworkStream ns = c.GetStream();
          
          

        }

        public string CreateMD5Hash(string input)
        {
            // Use input string to calculate MD5 hash
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));

            }
            return sb.ToString();
        }//end of create md5

        private void button1_Click(object sender, EventArgs e)
        {
          NetworkStream ns = c.GetStream();

            string st1 = textBox1.Text;
            string st2 = textBox2.Text;
            string st3 = comboBox1.Text;
           string passhash = CreateMD5Hash(st2);
            int lenght1 = st1.Length;
            int lenght2 = st2.Length;
            int length3 = st3.Length;


            char len;
            char len2;
            char len3;
            len = Convert.ToChar(lenght1);
            len2 = Convert.ToChar(lenght2);
            len3 = Convert.ToChar(length3);

            string name = string.Concat("F" + len + len2 + len3 + st1 + passhash + st3);
           
           byte[] buf = System.Text.Encoding.ASCII.GetBytes(name);  // convert string to an array of bytes
        ns.Write(buf, 0, name.Length);  // write to stream

          // here it accept permission from server to open new form
           byte[] buf2 = new byte[100];
       ns.Read(buf2, 0, 100);

           string add = System.Text.Encoding.ASCII.GetString(buf2);
           if(string.Compare(add,"1")==1)
            {
                this.Hide();
                studentform myform = new studentform();
                myform.Show();
            }
          
        }//end of button 1 click
        
    }//end of class form
}//end of namespac


and this is code for second form :

C#
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.Net;
using System.Net.Sockets;

namespace newform1
{
    public partial class Form2 : Form
    {
        TcpClient c = new TcpClient("127.0.0.1", 1000); 
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NetworkStream ns = c.GetStream();
           string stin = "1";
            byte[] buf = System.Text.Encoding.ASCII.GetBytes(stin);  // convert string to an array of bytes
           ns.Write(buf, 0, stin.Length);  // write to stream
            addremst myform = new addremst();
            this.Hide();
            myform.Show();
        }
    }
}


as i told before i gave one port to two form, it seems server doesn't accept connection from second form, i want them to use same port,
i have to many form, i don't want to give each one , port.
Posted
Updated 17-Jul-10 4:46am
v5
Comments
Kristian Sixhøj 16-Jul-10 8:28am    
Edit your question and include the relevant source code - you'll get help faster then.
[no name] 16-Jul-10 9:14am    
Can you provide more detail on your question, along with some code snippets which help us to
understand your problem in clear manner?
minakhazan 16-Jul-10 11:46am    
i edit my question.
minakhazan 16-Jul-10 11:47am    
i edit it.
Richard MacCutchan 16-Jul-10 12:10pm    
Are you sure your server program is still listening for a connection?

It's impossible to guess what your problem is without seeing some more of the code of the client and the server. Are you sure that your first form is closing the connection when it's finished? You also state that you are not sure if the server is staying open or even listening, so how can you expect it to work?
 
Share this answer
 
Comments
minakhazan 17-Jul-10 10:18am    
i update the question with code.
minakhazan 17-Jul-10 17:52pm    
how could i use tcpclient as public, so i can access it from different form without declaring it again.
because as you see in client side, i declare tcpclient in both form.
so it's one program, no need to declare twits, how can i do it?
I think your server code is only able to accept a single client connection. The following line:
TcpClient c = l.AcceptTcpClient();

is only called once, at the beginning of the program, so as soon as Form1 creates a connection the server will not check for any more. Also your while(true) loop does not appear to have any way to break out, thus blocking the whole program. You need some way to signal the end of the communication with Form1 and go back to waiting for a client connection, or separate your processing into threads to allow multiple connections at the same time.
 
Share this answer
 
Comments
minakhazan 17-Jul-10 11:37am    
thanks for your answer,
i get some tutorial form net about using threads.
i try to use it as i want with more than one form, but it also doesn't work.
here is code ,
server :

using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(1000);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;

            serverSocket.Start();
            Console.WriteLine(" >> " + "Server Started"); 

            counter = 0;
            while (true)
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();
                Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
                handleClinet client = new handleClinet();
                client.startClient(clientSocket, Convert.ToString(counter));
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> " + "exit");
            Console.ReadLine();
        }
    }

    //Class to handle each client request separatly
    public class handleClinet
    {
        TcpClient clientSocket;
        string clNo;
        public void startClient(TcpClient inClientSocket, string clineNo)
        {
            this.clientSocket = inClientSocket;
            this.clNo = clineNo;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();
        }
        private void doChat()
        {
            int requestCount = 0;
            byte[] bytesFrom = new byte[10025];
            string dataFromClient = null;
            Byte[] sendBytes = null;
            string serverResponse = null;
            string rCount = null;
            requestCount = 0;

            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);

                    rCount = Convert.ToString(requestCount);
                    serverResponse = "Server to clinet(" + clNo + ") " + rCount;
                    sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                }
            }
        }
    } 
}


and this is form 1 code :
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.Net;
using System.Net.Sockets;

namespace testthreadclient
{
    public partial class Form1 : Form
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
             msg("Client Started");
            clientSocket.Connect("127.0.0.1", 1000);
            label1.Text = "Client Socket Program - Server Connected ...";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NetworkStream serverStre

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