0

I need help with my situation. Erorr is "No connection could be made because the target machine actively refused it" when run client.Connect(). Thank you!

private void btnSend_Click(object sender, EventArgs e)
    {

        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8979);

        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP );
        client.Connect(ipEndPoint);


        Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hello server\n");
        client.Send(data);


        data = System.Text.Encoding.ASCII.GetBytes("quit\n");
        client.Send(data);

        client.Close();
    }

And this is server code, I checked it with telnet and it works well.

private void btnListen_Click(object sender, EventArgs e)
    {
        Thread serverThread = new Thread(StartUnsafeThread);
        serverThread.Start();
    }

    void StartUnsafeThread()
    {
        int bytesReceived = 0;
        byte[] recv = new byte[1];

        Socket clientSocket;

        Socket listenerSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

        IPEndPoint ipepServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8979);
        listenerSocket.Bind(ipepServer);

        listenerSocket.Listen(-1);

        clientSocket = listenerSocket.Accept();

        showCommand("New client connected");
        while (clientSocket.Connected)
        {
            string text = "";
            do
            {
                bytesReceived = clientSocket.Receive(recv);
                text += Encoding.UTF8.GetString(recv);
            } while (text[text.Length - 1] != '\n');
            showCommand(text);
        }
        listenerSocket.Close();
    }
Punfake
  • 1
  • 1

1 Answers1

0

I would recommend you to try the official Microsoft code example (with their detailed explanation) for async socket server

Server: https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example

Client: https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

y-me
  • 277
  • 4
  • 13