2

I'm making a simple chat application using TcpClient and TcpServer from System.Net.

I got everything working on my PC, the server communicates with the client and vice versa. But when I try to connect to the same server application using another PC (even on the same subnet as my PC) the thing doesn't work.

I've tried port-forwarding through my router, firewall and still nothing.

The Can you see me website says that the connection is being refused. Although!! Sometimes it says that the connection is timed out completely.

I am not sure what's wrong with my code or my PC, I would really appreciate some help from people that are more experienced in this area than I am.

Here is the configuration for the port forwarding in my router: Here is the configuration for the port forwarding thing in my rounter

If you need the code for the client and the server, here they are:

P.S. I make the change to the client in the BeginConnect() part at the bottom in order to change the IP address that I'm connecting to

Client:

using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace TcpTest_Client_
{
    public partial class Form1 : Form
    {
        TcpClient client;
        IPAddress localIP = null;
        bool connected = false;

        public Form1()
        {
            InitializeComponent();
        }

        public void clientConnectCallback(IAsyncResult result)
        {
            try
            {
                client.EndConnect(result);
                Log("Connected to " + client.Client.RemoteEndPoint);
                connected = true;

                NetworkStream clientStream = client.GetStream();

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

                while (true)
                {
                    bytesRead = 0;
                    try
                    {
                        //blocks until a client sends a message
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch (Exception ex)
                    {
                        //a socket error has occured
                        Log(ex.Message);
                        break;
                    }
                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        Log("Server on has disconnected");
                        break;
                    }

                    //message has successfully been received
                    UTF8Encoding encoder = new UTF8Encoding();
                    string bufferincmessage = encoder.GetString(message, 0, bytesRead);
                    Log("Server: " + bufferincmessage);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }

        public void Log(string msg)
        {
            richTextBox1.BeginInvoke(new Action(
            () =>
            {
                richTextBox1.Text += msg + "\n";
            }));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (addr.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = addr;
                    break;
                }
            }

            client = new TcpClient(AddressFamily.InterNetwork);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                client.BeginConnect(IPAddress.Parse("109.252.107.144"), 1234, clientConnectCallback, client);
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (connected)
            {
                UTF8Encoding encoder = new UTF8Encoding();
                NetworkStream clientStream = client.GetStream();

                byte[] stringToSend = new byte[richTextBox2.Text.Length];
                stringToSend = encoder.GetBytes(richTextBox2.Text);
                clientStream.Write(stringToSend, 0, stringToSend.Length);
            }
        }
    }
}

Server:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TcpTest
{
    public partial class Form1 : Form
    {
        private TcpListener server;
        private List<Thread> clientThreads = null;

        public Thread MainThread;

        public Form1()
        {
            InitializeComponent();
        }

        public void Log(string msg)
        {
            richTextBox1.BeginInvoke(new Action(
            () =>
            {
                richTextBox1.Text += msg + "\n";
            }));
        }

        public static string bufferincmessage;
        public void AcceptSocketPackets(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

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

            while (true)
            {
                bytesRead = 0;
                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch (Exception ex)
                {
                    //a socket error has occured
                    Log(ex.Message);
                    break;
                }
                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    Log("Client on " + tcpClient.Client.RemoteEndPoint + " has disconnected from the server");
                    break;
                }

                //message has successfully been received
                UTF8Encoding encoder = new UTF8Encoding();
                bufferincmessage = encoder.GetString(message, 0, bytesRead);
                Log("Client from " + tcpClient.Client.RemoteEndPoint + ": " + bufferincmessage);

                string stringToSend = "You sent me: " + bufferincmessage;
                byte[] messageToSend = new byte[stringToSend.Length];
                messageToSend = encoder.GetBytes(stringToSend);
                clientStream.Write(messageToSend, 0, messageToSend.Length);
            }
        }

        public void SocketAcceptCallback(IAsyncResult result)
        {
            TcpClient newClient = server.EndAcceptTcpClient(result);

            Log("Accepted client on " + newClient.Client.RemoteEndPoint);

            clientThreads.Add(new Thread(new ParameterizedThreadStart(AcceptSocketPackets)));
            clientThreads[clientThreads.Count - 1].Start(newClient);

            server.BeginAcceptTcpClient(SocketAcceptCallback, server);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MainThread = Thread.CurrentThread;
            clientThreads = new List<Thread>();

            try
            {
                IPAddress localIP = null;
                foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (addr.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localIP = addr;
                        break;
                    }
                }

                localIP = IPAddress.Any;
                // could also use this:
                // server = new TcpListener(new IPEndPoint(IPAddress.Any, 1234));
                server = new TcpListener(new IPEndPoint(localIP, 1234));

                Log("Starting server on " + localIP + ":1234");

                server.Start(6);

                server.BeginAcceptTcpClient(SocketAcceptCallback, server);

                Log("Started server on " + localIP + ":1234");
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }
    }

}
Michael
  • 548
  • 6
  • 23
  • Windows Firewall? – Richard Hubley Aug 29 '18 at 16:59
  • @RichardHubley, I've added two rules (inbound, outbound) for the port that I use. And actually disabled it as well. – Michael Aug 29 '18 at 17:01
  • 1
    Maybe another application is using port 1234. I try not to use port numbers other people with use. Best thing is to use cmd.exe >Netstat -a to make sure connections are working correctly. Also use cmd.exe >Ping IP or Computer Name. Try both IP and Computer name since one may work and the other may not work. Let me know the results and will help further. – jdweng Aug 29 '18 at 17:04
  • Thanks, @jdweng, I've checked the connections via >Netstat -a. I saw the only application working on that port, which was mine. Also, I tried pinging myself with different IPs: 127.0.0.1 (localhost), 192.168.1.11, my external IP, my Computer name - everything worked like a charm, no packet loss, no nothing. – Michael Aug 29 '18 at 17:14
  • 1
    Try doing reverse from Server PC back to your client. Sometimes ping works in one direction and not the other. If the port is blocked on Server the ping may still work due to the PING being implemented in the Ethernet card and not being blocked. – jdweng Aug 29 '18 at 17:18
  • @jdweng, just tried pinging one of my frinds PCs, everything worked, they got the packets, but not the other way around, they could not ping me for some reason... the got the timeout.. – Michael Aug 29 '18 at 17:36
  • By the way, forgot to mention, I thing this is not really important or related, but I've changed some stuff up in my Ethernet adapter options in windows. I set the internal IP to be static by manually configuring it like so: https://pp.userapi.com/c848624/v848624989/654b7/R0bWskeDPBk.jpg – Michael Aug 29 '18 at 17:41
  • they got*, i think* – Michael Aug 29 '18 at 17:46
  • If you are on the same router, don't use your external IP. Use the internal IP of the "server". I don't think you can send a message out from your router and have it sent back from your ISP – Richard Hubley Aug 29 '18 at 18:30
  • Changing IP addresses may take 45 minutes to an hour before the server will recognize the IP address. Rebooting the PC will speed up the time. A PC ARP its IP address when turned on or usually every 1/2 hour. Did you try ping in reverse using both IP and computer name? The port number could be blocked on the remote or the IP and mask wrong on server. I have debugged lots of these issues in the past. Know all the problems and fixes. – jdweng Aug 29 '18 at 18:50
  • You ISP may not be advertising your IP out on the network. I would ping your friend. Then have him check his ARP table using cmd.exe >ARP -a. He should see your IP address in the table. Then he should be able to ping back to you on same IP. Once a ping works in one direction all the routers then have your IP and should be able to return through same routers for up to 1/2 hour (time the ARP table removes entries). – jdweng Aug 29 '18 at 19:01
  • Thanks for the help, @jdweng. I'll try those methods as soon as I get home and will reply. – Michael Aug 29 '18 at 20:01

1 Answers1

-1

C++ is giving me problems like that. Try creating another project, paste the server code and build it as Release x86. If you change the build target and our problem is the same, windows firewall, even when turned off, won't allow the server or the client to run without any exception. If it doesn't work I might not know the answer.

  • How is c++ related to c#? – Uwe Keim Aug 29 '18 at 17:20
  • It must be a windows problem. With me it was. That might be the case for him too. As I couldn't find any answer online for my problem and I spent hours dealing with it I decided to help someone that has a problem like mine and just suggest doing this. It might not work but it is a hypothesis taken down – A cool programmer Aug 29 '18 at 18:04