Tcp Server adds the client name to a lisbox

Asked

Viewed 48 times

0

I have a server and a client, when the client connects it adds the Client ip to a server listbox, appears as if an item is added (in listbox) but does not appear ip, this is the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Collections;

namespace Controlo
{
    public partial class MainMenu : Form
    {
        public MainMenu()
        {
            InitializeComponent();
        }
        //PrivateINI bools
        private TcpListener tlsClient;
        private Thread thrListener;
        bool ServRunning = false;
        private IPAddress ipAddress;
        TcpClient tcpClient;
        //set Max Users
        public static Hashtable htUsers = new Hashtable(900);
        //Set Max Connections
        public static Hashtable htConnections = new Hashtable(900);
        public static string aux = "";

        //Btn Start Server
        private void BtnStart_Click(object sender, EventArgs e)
        {
            if (ServRunning == false)
            {
                //TxtNoIp text = ""
                if (TxtNoIp.Text == "")
                {
                    MessageBox.Show("Please insert NoIp Host Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                //TxtPort text = ""
                else if (TxtPort.Text == "")
                {
                    MessageBox.Show("Please insert a port", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                //Start Server
                else
                {
                    //IpAdress
                    IPAddress iplocal = IPAddress.Parse(TxtNoIp.Text);

                    //Port
                    tlsClient = new TcpListener(Convert.ToInt32(TxtPort.Text));

                    //Start
                    tlsClient.Start();

                    //Set Server running true
                    ServRunning = true;

                    //Keep Listening
                    thrListener = new Thread(KeepListening);
                    thrListener.Start();
                    BtnStart.Text = "Disconect";
                    TxtNoIp.Enabled = false;
                    TxtPort.Enabled = false;
                }
            }
            else
            {
                //Stop
                tlsClient.Stop();

                //Set server running false
                ServRunning = false;

                //Stop Listening
                thrListener.Abort();

                //Set Txt Port & no ip true
                BtnStart.Text = "Connect";
                TxtPort.Enabled = true;
                TxtNoIp.Enabled = true;
            }
        }
        private void KeepListening()
        {
            while (ServRunning == true)
            {
                // Accept a pending connection
                tcpClient = tlsClient.AcceptTcpClient();
                // Create a new instance of Connection
                Connection newConnection = new Connection(tcpClient);
                if (aux != "")
                    LBClient.Items.Add(aux);
            }
        }
        public static void AddUser(TcpClient tcpUser, string strUsername)
        {
            //Stablish Connection
            MainMenu.htUsers.Add(strUsername, tcpUser);
            MainMenu.htConnections.Add(tcpUser, strUsername);
            //aux = strUsername;

        }

        private void MainMenu_Load(object sender, EventArgs e)
        {

        }
    }

    class Connection
    {

        TcpClient tcpClient;
        private Thread thrSender;
        private StreamReader srReceiver;
        private StreamWriter swSender;
        private string currUser;
        private string strResponse;
        public static string aux = "";
        //private static StatusChangedEventArgs e;

        // The constructor of the class takes in a TCP connection
        public Connection(TcpClient tcpCon)
        {
            tcpClient = tcpCon;
            // The thread that accepts the client and awaits messages
            thrSender = new Thread(AcceptClient);
            // The thread calls the AcceptClient() method
            thrSender.Start();
        }
        public void CloseConnection()
        {
            // Close the currently open objects
            tcpClient.Close();
            srReceiver.Close();
            swSender.Close();
        }
        private void AcceptClient()
        {
            srReceiver = new System.IO.StreamReader(tcpClient.GetStream());
            swSender = new System.IO.StreamWriter(tcpClient.GetStream());

            // Read the account information from the client
            currUser = srReceiver.ReadLine();

            // We got a response from the client
            if (currUser != "")
            {
                // Store the user name in the hash table
                if (MainMenu.htUsers.Contains(currUser) == true)
                {
                    // 0 means not connected
                    swSender.WriteLine("0|This username already exists.");
                    swSender.Flush();
                    CloseConnection();
                    return;
                }
                else if (currUser == "Administrator")
                {
                    // 0 means not connected
                    swSender.WriteLine("0|This username is reserved.");
                    swSender.Flush();
                    CloseConnection();
                    return;
                }
                else
                {

                    // 1 means connected successfully
                    swSender.WriteLine("1");
                    swSender.Flush();

                    // Add the user to the hash tables and start listening for messages from him

                    MainMenu.AddUser(tcpClient, currUser);
                    MainMenu frm = new MainMenu();
                    frm.LBClient.Items.Add(tcpClient.ToString());
                    frm.LBClient.Update();
                }
            }
            else
            {
                CloseConnection();
                return;
            }
        }
        public static void SendAdminMessage(string Message)
        {
            //MainMenu frm = new MainMenu();
            //e = new StateChangeEventArgs(frm.LBClient.Items.Add());

        }
    }
}

I forgot to warn what happens is the following the client sends a string saying his ip the client receives but does not show listbox, I noticed that this was happening.

            MainMenu.AddUser(tcpClient, currUser); //Executa
            MainMenu frm = new MainMenu(); //Executa
            frm.LBClient.Items.Add(tcpClient.Client.LocalEndPoint); //Não Executa
            frm.LBClient.Update(); //Não Executa

I had to see again and actually execute what happens is that it adds an iteam just doesn’t give the name to the iteam.

1 answer

0

Peter,

To show the IP address of the connected client you are using:

tcpClient.ToString()

The correct thing would be to use:

tcpClient.Client.LocalEndPoint

I hope I’ve helped, despite the short answer.

  • It does not work because the client sends a string telling its ip what I mer realized is that it does not execute the code for example runs MainMenu frm = new MainMenu(); executes MainMenu.htUsers.Add(strUsername, tcpUser); but does not perform frm.LBClient.Items.Add(strUsername.ToString()); and it’s all followed I’ll give an update

Browser other questions tagged

You are not signed in. Login or sign up in order to post.