.NET 4 new TCP client fails to connect: No connection could be made because the target machine actively refused it
I am having a simple issue with .NET 4 Sockets (TcpClient) in both win7 and xp.
I get the error:
No connection could be made because the target machine actively refused it
This does not appear to be a firewall issue, since both the client and the server programs are on the same computer, and I don't have any local f开发者_StackOverflowirewall enabled.
I wrote both the server and client (they are talking on port 80 (I have also tried other ports such as 31000). Nothing else is running on port 80 on my machine.
The client code is:
public void makeConnection()
{
string server = ClientStatus.myself.ServerName;
port = 80;
ClientStatus.myself.BytesSent = 0.ToString();
client = new TcpClient(server, port);
ClientStatus.myself.Connected = "connected";
stream = client.GetStream();
bytes = new Byte[1024];
}
and I confired that the server and port are what I expect. The error occurs on new TcpClient(server, port), and it spins for about 4 seconds before the error occurs. I have also tried using an IP address (127.0.0.1) instead of "myhostname.domain.com" as the server (the alternate way to create a client socket) and it also fails.
Here is the code for the server that I wrote:
namespace SocketListener { class DataListener { public static DataListener myself; TcpListener server = null; Byte[] bytes; Int32 port; IPAddress localAddr; MainWindow w;
public DataListener(MainWindow caller)
{
DataListener.myself = this;
w = caller;
Status.myself.Connected = "starting";
port = 80;
localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
bytes = new Byte[1024];
server.Start();
}
public void acceptLoop()
{
TcpClient client;
while (true)
{
// Perform a blocking call to accept requests.
Status.myself.Connected = "waiting";
if (server.Pending())
{
client = server.AcceptTcpClient();
Status.myself.Connected = "true";
Status.myself.BytesReceived = 0.ToString();
NetworkStream stream = client.GetStream();
dataLoop(stream);
client.Close();
}
else
{
Thread.Sleep(100);
return;
}
// Shutdown and end connection
Status.myself.Connected = "false";
}
}
public void dataLoop(NetworkStream stream)
{
int count = 0;
int i;
Status.myself.ByteRate = "0.0";
Stopwatch watch = new Stopwatch();
watch.Start();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
count += i;
Status.myself.BytesReceived = count.ToString();
}
watch.Stop();
double rate = count / (watch.ElapsedMilliseconds / 1000);
rate = rate / (1024 * 1024);
Status.myself.ByteRate = rate.ToString();
}
public void shutdown()
{
server.Stop();
}
}
}
I have win7 box. So accepting incomming connections is blocked (even local). The answer is:
run
netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user
see:
netsh http add urlacl : add reservation for a group
精彩评论