hi all, i have the server code and client code, but it cannot communicating with each other. i try to run it in 2 pc but happen error. i do not know what is the problem, please help me.

server 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; //networking
using System.Net.Sockets; //networking
using System.Threading; //networking
using System.Net.NetworkInformation; //monitor bandwidth


namespace NBCS_serverlogin
{
    public partial class NBCSadmin : Form
    {

        private TcpListener tcpListener;
        private Thread threadTcp;
        static NetworkStream clientNetStream;
        const int portnumber = 3333;

       // public delegate void ChangedEventHandler(object sender, EventArgs e);
        //public event ChangedEventHandler Changed;

        public NBCSadmin()
        {
            InitializeComponent();
            portnotxt.Text = "3333";
            //initiateListen();
        }

        private void initiateListen()
        {
            //Tcp
            this.tcpListener = new TcpListener(IPAddress.Any, portnumber);
            System.Convert.ToInt16(portnotxt.Text.Trim());
            this.threadTcp = new Thread(new ThreadStart(ListenToClients));
           // this.threadTcp.Start();
         

        }

        //listen for connected client 
        private void ListenToClients()
        {
            tcpListener.Start(); 

            while (true)
            {
                try
                {
                    // block till client connect to server
                    TcpClient clientCom = this.tcpListener.AcceptTcpClient(); 

                    //handle connected clients
                    Thread threadClient = new Thread(new ParameterizedThreadStart(HandleClients));
                    threadClient.Start(clientCom);
                    

                }
                catch (Exception)
                {
                    MessageBox.Show ("error");
                }
            }
        }
        private void HandleClients(object clientCom)
        {
            TcpClient tcpClient = (TcpClient)clientCom;
            clientNetStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    bytesRead = clientNetStream.Read(message, 0, 4096);
                }

                catch (Exception)
                {
                    // error happened
                    break;
                }

                if (bytesRead == 0)
                {
                    // client diconnected to server
                    constatuslabel.Text = "Client has disconnected from the server.";
                    break;
                }

                //msg has been successfully received
                ASCIIEncoding asciiEncoder = new ASCIIEncoding();
                // output msg
                constatuslabel.Text = tcpClient.Client.LocalEndPoint + "" + tcpClient.Client.RemoteEndPoint + asciiEncoder.GetString(message, 0, bytesRead);

                //System.Diagnostics.Debug.WriteLine(asciiEncoder.GetString(message, 0, bytesRead));
            }
            // (button)
            tcpClient.Close();
        }
                      
        private void connecttoclientbtn_Click_1(object sender, EventArgs e)
        {       
            initiateListen();
            constatuslabel.Text = "Waiting for a connection...";
                        
        }

       private void portnotxt_TextChanged(object sender, EventArgs e)
        {

        }
     
    }
     
   }

client 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;
using System.Threading;
using System.IO;

namespace NBCS_Client
{
    public partial class NBCSuser : Form
    {
        private TcpClient clientuser;
        private IPEndPoint serverEndPoint;
        private NetworkStream clientStream;
      
        const int portnumber = 3333;

       
        public NBCSuser()
        {
           
            InitializeComponent();
           // initiateListenUser();
            ipaddtxt.Text = "127.0.0.1";
            portnotxt.Text = "3333";
        }


        public void initiateListenUser()
        {
            clientuser = new TcpClient();

            //get the remote ip add
            IPAddress ipaddress = IPAddress.Parse(ipaddtxt.Text.Trim());
            System.Convert.ToInt16(portnotxt.Text.Trim());
            //create end point
            serverEndPoint = new IPEndPoint(ipaddress, portnumber);

        }

        public void connectTcpServer()
        {
            clientuser.Connect(serverEndPoint); //10061 error
            clientStream = clientuser.GetStream();

            //create thread to handle communication with connected client
            Thread threadClient = new Thread(new ParameterizedThreadStart(HandleClients));
            threadClient.Start(clientuser);

        }

        public void HandleClients(object clientuser)
        {
            TcpClient tcpclient = (TcpClient)clientuser;
            NetworkStream clientStream = tcpclient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    //block until client send a msg
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch (SocketException)
                {
                    //socket error
                    break;
                }

                if (bytesRead == 0)
                {
                    //client disconnected to server
                    break;
                }
                //msg received successfully
                ASCIIEncoding asciiEncoder = new ASCIIEncoding();
                // output msg
                userconstatuslabel.Text = tcpclient.Client.LocalEndPoint + "" + tcpclient.Client.RemoteEndPoint + asciiEncoder.GetString(message, 0, bytesRead);
                //textFrmServer 

            }
            tcpclient.Close();

        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void exitbtn_Click(object sender, EventArgs e)
        {
            
            Application.Exit();
        }

        private void connectbtn_Click(object sender, EventArgs e)
        {
            initiateListenUser();
            connectTcpServer();
            userconstatuslabel.Text = "Connecting to server...";
        }


    }
}

And your error message was...?

Put Listener.Start() method, just under where you create a reference of TcpListener, so like:

private void initiateListen()
{
    //Tcp
    this.tcpListener = new TcpListener(IPAddress.Any, portnumber);
    tcpListener.Start(); //HERE!!
    //why you have this code bellow??
    //you need a new variable to get Port no:
    int intPort = Convert.ToInt32(portnotxt.Text.Trim());
    this.threadTcp = new Thread(new ThreadStart(ListenToClients));
}

And your error message was...?

sorry, my bad, when i run, line 49 error (client code)

clientuser.Connect(serverEndPoint); //10061 error

i search on msdn website, found out was this error:
Connection refused.
No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.

i really do not know whether is my server code wrong or client code wrong, i cannot figure out why it happen. Connection of both client server cannot be established. Please help.

Thanks again.

Put Listener.Start() method, just under where you create a reference of TcpListener, so like:

private void initiateListen()
{
    //Tcp
    this.tcpListener = new TcpListener(IPAddress.Any, portnumber);
    tcpListener.Start(); //HERE!!
    //why you have this code bellow??
    //you need a new variable to get Port no:
    int intPort = Convert.ToInt32(portnotxt.Text.Trim());
    this.threadTcp = new Thread(new ThreadStart(ListenToClients));
}

Thank you so much Mitja! thank you for helping me. So far no error appear, but i think there are still something wrong in the way i code, because it didn't show anything or text that shows that the connection is established between this two when i run the programs, so i do not know whether there are connection really exist between both server client.

if possible please help me, thanks thanks.

sorry, my bad, when i run, line 49 error (client code)

clientuser.Connect(serverEndPoint); //10061 error

i search on msdn website, found out was this error:
Connection refused.
No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.

i really do not know whether is my server code wrong or client code wrong, i cannot figure out why it happen. Connection of both client server cannot be established. Please help.

Thanks again.

So far no error appeared after the guidance by Mitja, but the program didn't show anything that tells there is connection between client and server, something wrong in both codes.

please help again if possible, thanks thanks.

It would be a good idea to put some error handling around networking code. Fortunately, C# has a try/catch/finally construct for situations like this...

try
{
   //put your network code here
}
catch (SocketException se) 
{
   //put code here to handle a socket error (message box or a log file perhaps?)
}
catch (Exception e)
{
   //this error is probably unexpected, so may need to be handled differently than 
   //a simple network error
}
finally
{
  //this code is guaranteed to be run regardless of if there was an error or not  
}

Check here for some ideas how to do the server-client projects.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.