Basic Problem: I have made a server program and a client program. When I try to use the client to connect to 127.0.0.1 or my LAN IP, the program connects and transfers information successfully. However, when I get somebody else to host the server, or when I try to connect to a server on my own machine using my WAN IP, I currently get a "Connection could not be made because the target machine actively refused it." exception. I'm not sure what I changed to get this exception I just mentioned instead, but I was previously getting a "Connection could not be made because the target machine did not respond." exception as well.
Here is the jist of the code causing the problem:
Information Initialization Code:
Expand|Select|Wrap|Line Numbers
- internal Connection(int port)
- {
- DNSname = Dns.GetHostName();
- IPAddress ip = Dns.GetHostEntry(DNSname).AddressList[0];
- address = new IPEndPoint(ip, port);
- }
Expand|Select|Wrap|Line Numbers
- TcpListener Listener = new TcpListener(IPAddress.Any, address.Port);
- Listener.ExclusiveAddressUse = false;
- Listener.Start(10);
- while (Active)
- {
- if (Listener.Pending())
- {
- if (RemoteTcps.Count < CommonConstants.MAX_PLAYERS)
- {
- Thread ConnectThread = new Thread(delegate() { ConnectToClient(Listener); } );
- ConnectThread.Start();
- }
- }
- Thread.Sleep(100);
- }
- Listener.Stop();
Client code:
Expand|Select|Wrap|Line Numbers
- internal void StartAsClient(IPEndPoint serverIP)
- {
- Active = true;
- Tcp = new TcpClient(this.address);
- remoteaddress = serverIP;
- if (ConnectToServer())
- {
- Thread ClientThread = new Thread(delegate() { LiveClientConnection(); });
- ClientThread.Start();
- }
- }
- private bool ConnectToServer()
- {
- try
- {
- Tcp.Connect(remoteaddress);
- return true;
- }
- catch (Exception exception)
- {
- Debug.Error(2, "Connection " + address.Address.ToString() + ":" + address.Port + " to " + remoteaddress.Address + ":" + remoteaddress.Port + " failed. " + exception.Message, this);
- return false;
- }
- }
The catch() above in the client code is what is telling me that Connect() failed because the server machine actively refused it.
I have made sure to turn off windows firewall completely for testing, and I have only been using forwarded ports on my router when I host. I have also tried putting the server on somebody else's computer and tried connecting to him through his WAN address, with no prevail, and he doesn't use a firewall, his router is forwarded, and he can successfully host other programs.
I used the MSDOS prompt to ping my WAN address and that was successful.
Someone with a similar problem in another forum was told to use TcpListener Listener = new TcpListener(Dns .GetHostEntry(D ns.GetHostName( )).AddressList[0], address.Port); instead, but that didn't work for me and I think IPAddress.Any is probably what should be used.
Thanks in advance for any help.