HI,
I am very new to C# socket. I have tried several very simple code, but all of them lead to same error message:

System.Net.Sockets.SocketException: No connection could be made because the target
machine actively refused it 127.0.0.1:7
at System.Net.Sockets.TcpClient..ctor(String hostname, Int32 port)
at MainClass.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 14

Below is one of the example code.

I searched though the net, but could not figure out it. :(
I have turned the firewall off. The code is running on win7.
Can someone point me the way out. As this is my first time programming for socket, please give more detail if possible. Thanks a lot.

using System;
using System.IO;
using System.Net.Sockets;

class MainClass
{
  const int echoPort = 7;

  [STAThread]
  static void Main(string[] args)
  {
    using ( TcpClient tc = new TcpClient( "localhost", echoPort ) ) // <-- get exception here
    {
      NetworkStream ns = tc.GetStream();
      StreamWriter sw = new StreamWriter( ns );
      StreamReader sr = new StreamReader( ns );

      sw.WriteLine( "test message" );
      sw.Flush();
      System.Console.WriteLine( sr.ReadLine() );
    }
  }
}

Recommended Answers

All 2 Replies

Hi,

first of all, try using port number bigger then 1000. Windows reserves many of them for different applications. put echoPort, 5000 for example.
Second, on the localhost there is any TCPServer that runs? When you try to connect through this code

using (TcpClient tc = new TcpClient("localhost", echoPort);

you try to reach a server on "localhost" that listens to port number 7. If there is no application listening on that port, an exception is raised.
Also check link link, you may find some usefull information.

Ionut

To answer your question, it's because nothing is listening on port 7. This is actually from an old echo service that used to run but is no longer in action once ICMP came into effect.

If you wish to test the "echo" response, you need to create an ICMP message that is "type 7" (which is where the misconception comes from that it is port 7)

If you wish to create your own server, you can create a very simple echo service yourself =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.