Reputation: 3324
I am trying to forward multiple sockets communication to a target socket. So I need to make multiple connection to that target socket, but when I try to connect to it for the second time, I get this:
SocketException: No connection could be made because the target machine actively refused it
I think the problem is with the other end of the socket, i.e port and host and because there is already a connection between port related to my program and target port, to have a second connection I need a second port for my program. I hope my problem be clear for you guys. Any Idea how to do it?
This is a test program just to show the problem.
using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
class Sample
{
private static ManualResetEvent connectDone = new ManualResetEvent(false);
public static void Main()
{
Socket[] s = new Socket[10];
for (int i = 0; i < s.Length; i++)
{
IPAddress ipAddress;
ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndp = new IPEndPoint(ipAddress, 1100);
// Create a TCP/IP socket.
s[i] = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
connectDone.Reset();
s[i].BeginConnect(localEndp,
new AsyncCallback(ConnectCallback), s[i]);
connectDone.WaitOne();
s[i].Send(Encoding.ASCII.GetBytes(i.ToString() + ": hi.\r\n"));
}
}
private static void ConnectCallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
// Signal that the connection has been made.
connectDone.Set();
}
}
I even tried to bind my sockets to different ports, but still second socket gets that exception.
Upvotes: 1
Views: 2254
Reputation: 171188
This error message means that there is no open port on that IP. The IP is valid but the remote host replied that it will not accept a connection on this port.
You should be getting this error even for the very first connection.
Find out why the port is not open.
Btw, you use of async connect is counter-productive. You have non of the async benefits and all of the disadvantages. But this is not the point of this question.
Upvotes: 1