Question

I building a client/server chat app , where the server is listening on IP number 127.0.0.1 and port 1212 , and clients are supposed to connect to that IP & Port .

The problem - in the following order :

  1. I run the server on my computer , listening on (127.0.0.1 & port 1212)

  2. I'm also running a client on my computer (the same computer as #1) that successfully connects to the server (127.0.0.1 & port 1212)

  3. I'm running another client from a different IP , but when trying connect to the server (127.0.0.1 & port 1212) the attempt failed . In this IP , I do not run another server !!!

I don't understand the reason for that ... here is the code :

Server side :

public partial class ServerForm : Form
{
    private TcpListener m_tcpServer;
    private TcpClient m_tcpClient; 
    private Thread th;
    private ServerNotifier m_chatDialog;
    private List<ServerNotifier> m_formArray = new List<ServerNotifier>();
    private ArrayList m_threadArray = new ArrayList();
    public delegate void ChangedEventHandler(object sender, EventArgs e);
    public event ChangedEventHandler m_Changed;
    public delegate void SetListBoxItem(String str, String type); 


    // some code 

   public void StartListen() 
    {             
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");
        m_tcpServer = new TcpListener(localAddr, Int32.Parse(tbPortNumber.Text));
        m_tcpServer.Start();

        // Keep on accepting Client Connection
        while (true)
        {               
            // New Client connected, call Event to handle it.
            Thread t = new Thread(new ParameterizedThreadStart(NewClient));
            m_tcpClient = m_tcpServer.AcceptTcpClient();
            t.Start(m_tcpClient);                 
        }
    }




}

The winform of the server ....

enter image description here

Client side :

public partial class ClientForm : Form
{

    // to know when a button was clicked
    private bool m_connectionEstablished = false;
    private bool m_enterKeyPressed = false;
    private bool m_notRunning = false;        // flip this when the server is not running
    private NetworkStream m_ns = null;
    private StateObject m_state = null;
    private TcpClient m_clientTcpConnection = null;

    // ip and m_username entered by the client
    private String m_ipNumberString = String.Empty;
    private String m_username = String.Empty;
    private int m_port = 0;

    public bool StartTheClient(int m_port)
    {
        byte[] data = new byte[1024];
        string inputFromClient = "";            
        string portString = "";

        try
        {
            // "127.0.0.1"
            this.m_clientTcpConnection = new TcpClient(this.m_ipNumberString , this.m_port);
        }

        catch (Exception e)
        {
            // this.rtbClientChat.SelectionColor = Color.LimeGreen;
            this.m_notRunning = true;  // m_clientTcpConnection is not running
            MessageBox.Show("The server is currently not running , try again later!");
            // connection failed
            return false;  
        }

        this.rtbClientChat.SelectedText = "Connected to the Server...";
        String local_IP = ((IPEndPoint)m_clientTcpConnection.Client.LocalEndPoint).Address.ToString();
        String local_Port = ((IPEndPoint)m_clientTcpConnection.Client.LocalEndPoint).Port.ToString();
        this.rtbClientChat.SelectedText = "\nConnected on IP address " + local_IP + " and Port " + local_Port;
        this.rtbClientChat.SelectedText = "\nEnter a message to send to the Server";


        this.m_ns  =  m_clientTcpConnection.GetStream();
        this.m_state = new StateObject();
        this.m_state.workSocket = m_clientTcpConnection.Client;
        this.m_clientTcpConnection.Client.BeginReceive(m_state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(OnReceive), m_state);
        // connection established successfully
        this.m_connectionEstablished = true;
        return true;

    }





   /// <summary>
    /// connet/disconnect
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (this.connectionLabel.Checked == true)
        {
            // then the user checked the "connet/disconnect" checkbox 
            // now check if the user also filled the m_port number 

            try
            {                    
                // trying to check if the user entered something is the m_port box
                // grab port number 
                m_port = Int32.Parse(this.boxPortNumber.Text);
                m_ipNumberString = this.ipBoxNumber.Text;

                // grab IP number
                if (m_ipNumberString == string.Empty)
                {
                    MessageBox.Show("Please enter a valid IP Number!");
                    this.connectionLabel.Checked = false;
                    return;
                }

                // grab username
                this.m_username = this.usernameBox.Text;
                if (this.m_username == string.Empty)
                {
                    MessageBox.Show("Please enter a Username!");
                    this.connectionLabel.Checked = false;
                    return;
                }
                StartTheClient(m_port);

            }
            catch (Exception exp)
            {
                if (this.m_notRunning == true)    
                {
                    // then the user tried to initiate connection
                    // while the m_clientTcpConnection is disconnected 
                    this.m_notRunning = false;
                }
                else
                {
                    // the user didn't put anything in the m_port box
                    MessageBox.Show("Please enter a Port number !");
                    this.connectionLabel.Checked = false;
                }

            }
        }
    }

Its winform :

enter image description here

Any idea why this is happening ?

Much appreciated !

Était-ce utile?

La solution

127.0.0.1 is a localhost. You should specify the IP of the server in the network. You can easily find the IP of the server by running ipconfig in command prompt. And the listener should also be started on that IP address.

Autres conseils

127.0.0.1 In computer networking, localhost means this computer. So if you run your client on another pc, it will try to connect to the server on that pc, but your server is on another. Set the client IP to the one where you have the server.

127.0.0.1

In case if you have more than one network interface on the server you should start your listener like this, for more details follow the link:

m_tcpServer = new TcpListener(IPAddress.Any, Int32.Parse(tbPortNumber.Text));

TcpListener Constructor

Every device has its own localhost (127.0.0.1).

You cannot connect to another PC localhost (127.0.0.1), so your server should have IP such as 192.168.0.1 with specified port which is reachable from another PC.

If not, everytime it will only try to connect to its own localhost!

normally we just use localhost to test our network program internally. but it won't success if you want test externally with localhost.

127.0.0.1 on any machine refers to itself ( localhost) . So your client code on different machine need to refer to a server IP. Every machine has two IP's one is internal 127.0.0.1 and other can be external like 192.168.1.10

You need to provide the client code with a external IP address in that LAN

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top