C# Socket Refusing Public Connection

Asked

Viewed 5,312 times

3

I am using the server and client example below to make a TCP connection via internet and in the client returns the following message:

Additional information: No connection could be made because the target machine actively refused them

The door 5902 via public IP is released, I used another software that opens a TCP connection on that same port and testing with telnet via public IP, connected normally.

Server

using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Diagnostics;

namespace Server
{
    class Server
    {
        static ManualResetEvent allDone = new ManualResetEvent(false);

        private static void ThreadInfos()
        {
            while (true)
            {
                Console.Title = "Unity C# Server - Threads: " + Process.GetCurrentProcess().Threads.Count.ToString();
                Thread.Sleep(1000);
            }
        }

        static void Main(string[] args)
        {
            //Thread to show infos on console title
            Thread thread = new Thread(new ThreadStart(ThreadInfos));
            thread.Start();

            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 5902);
            Console.WriteLine("Local address and port : {0}", localEP.ToString());

            Socket listener = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(localEP);
                listener.Listen(10);

                while (true)
                {
                    allDone.Reset();

                    Console.WriteLine("Waiting for a connection...");
                    listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);

                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("Closing the listener...");
        }

        static void AcceptCallback(IAsyncResult ar)
        {
            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Signal the main thread to continue.
            allDone.Set();

            // Create the state object.
            StateObject state = new StateObject();
            state.WorkSocket = handler;
            handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.WorkSocket;

            // Read data from the client socket.
            int read = handler.EndReceive(ar);

            // Data was read from the client socket.
            if (read > 0)
            {
                Console.WriteLine("[{0}] read {1} bytes", Thread.CurrentThread.ManagedThreadId, read);
                //state.sb.Append(Encoding.ASCII.GetString(state.Buffer, 0, read));
                handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
            }
            else
            {
                /*if (state.sb.Length > 1)
                {
                    // All the data has been read from the client;
                    // display it on the console.
                    string content = state.sb.ToString();
                    Console.WriteLine("[{0}] Read {1} bytes from socket.\n Data : {2}",
                       Thread.CurrentThread.ManagedThreadId, content.Length, content);
                }*/
                handler.Close();
            }
        }

        public class StateObject
        {
            public Socket WorkSocket = null;
            public const int BufferSize = 1024;
            public byte[] Buffer = new byte[BufferSize];
            //public StringBuilder sb = new StringBuilder();
        }
    }
}

Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("201.35.xxx.xxx"), 5902);

            Socket s = new Socket(remoteEP.Address.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);
            s.Connect(remoteEP);

            Console.WriteLine("Connected, sending a few bytes...");

            byte[] bytes = Encoding.ASCII.GetBytes("test");

            while (true)
            {
                s.Send(bytes);
            }

            s.Close();
            s.Dispose();
        }
    }
}
  • 1

    The firewall is disabled.

  • 4

    I discovered the problem, I have a service (Viewer VNC) that starts together with Windows on that same port, I changed the port and connected perfectly. Strange is that the framework did not generate any Exception saying that the port was already in use, will understand.

  • 5

    This question seems to be decontextualized because it is about an individual problem that cannot be reproduced and will not help other people.

1 answer

1

Reply given in comment: The problem was caused because the OP has a service(VNC Viewer) starting along with Windows using that same port, the port has been changed and connected in an expected way.

Browser other questions tagged

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