Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi Team

I have a problem with my WPF window application, basically the application is sending a request to server application(echotool.exe) which must reads the data as a json and then TCP client must be able to see this back as responce. Problem now my application when i debug is throwing this server/network connection refuse. the IP is
127.0.0.1
and port is 12345. I am using putty to telnet using this IP address and port for testing my code.

The issue gets this connection refuse to a target machine on this line when debug
await using NetworkStream stream = Client.GetStream();
No firewall or ports conflict i tested and no issue found. Could i need to implement a server code to achieve this if so please assist me.

What I have tried:

C#
//Back end

<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace PingServerApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

           
        }

        // declaring some local variables and method for clicking buttons.

        bool eco = false;
        async void OnClick1(object sender, RoutedEventArgs e)
        {
            // add to datagrid
            dataGrid.Items.Clear();
            await TcpRequest();
        }

       

        void OnClick2(object sender, RoutedEventArgs e)
        {
            eco = false;
        }
        class Body { public Guid Id { get; set; } }

        // class for model

        public class TCPConnectionModel
        {
            public TimeOnly Started { get; set; }
            public TimeOnly Processed { get; set; }
            public TimeSpan Elapsed { get { return Processed - Started; } set { } }
        }

        // TCPRequest for body and serialize and deserialize json data

        async Task TcpRequest()
        {
            try
            {

                // initiate tcp
                IPHostEntry IpHostInfo = Dns.GetHostEntry("127.0.0.1");
                IPAddress IpAddress = IpHostInfo.AddressList[0];

                // initiate endPoint
                var endPoint = new IPEndPoint(IpAddress, 12345);

                // starting tcp client
                using TcpClient Client = new TcpClient();
                await Client.ConnectAsync(endPoint);
                await using NetworkStream stream = Client.GetStream();
                eco = true;
                while (eco)
                {

                    // start timer
                    TCPConnectionModel displayData = new() { Started = TimeOnly.FromDateTime(DateTime.Now) };

                    // initiate send data
                    Body requestBody = new() { Id = Guid.NewGuid() };

                    //initiate recieve data
                    var buffer = new byte[1_024];

                    // Json Serialize
                    string jsonString = JsonSerializer.Serialize(requestBody);

                    // tcp send
                    await stream.WriteAsync(Encoding.ASCII.GetBytes(jsonString));

                    // tcp recieve and decode
                    int received = await stream.ReadAsync(buffer);
                    var message = Encoding.UTF8.GetString(buffer, 0, received);

                    // json Deserialize
                    Body? recievedBody = JsonSerializer.Deserialize<Body>(message);

                    // stop timer
                    displayData.Processed = TimeOnly.FromDateTime(DateTime.Now);

                    // delay for 500ms
                    Thread.Sleep(500);

                    // add to datagrid
                    dataGrid.Items.Add(displayData);

                    // display result in status bar
                    resultveiw.Text = message;
                }
            }
            catch (Exception ex)
            {
                resultveiw.Text = ex.Message;
            }
        }
    }
}


// EchoTest Server listens to 12345
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using SimpleTCP;
using System.IO;

namespace GUI
{
    /// <summary>
    /// Interaction logic for EchoWindowTest.xaml
    /// </summary>
    public partial class EchoWindowTest : Window
    {
        public EchoWindowTest()
        {
            InitializeComponent();
        }

        SimpleTcpServer server;


        public class DisplayData
        {
            public TimeOnly Started { get; set; }
            public TimeOnly Processed { get; set; }
            public TimeSpan Elapsed { get { return Processed - Started; } set { } }
        }
        private void MainWindow_Load(object sender, EventArgs e)
        {
            try
            {

                DisplayData displayData = new() { Started = TimeOnly.FromDateTime(DateTime.Now) };
                displayData.Processed = TimeOnly.FromDateTime(DateTime.Now);
                server = new SimpleTcpServer();
                server.Delimiter = 0 * 13;
                server.StringEncoder = Encoding.UTF8;
                server.DataReceived += Server_DataReceived;




                Thread.Sleep(500);
                dataGrid.Items.Add(displayData);



            }
            catch (Exception ex)
            {
                txtStatus.Text = ex.Message;
            }
        }
        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            txtStatus.Dispatcher.Invoke(new Action(delegate
            {
                txtStatus.Text += e.MessageString;

            }));
        }

        public void btnStart_Click(object sender, RoutedEventArgs e) /*Start button*/
        {
            txtStatus.Text += "Server starting ...";
            System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(txtHost.Text));
            server.Start(ip, Convert.ToInt32(txtPort.Text));



        }

        public void btnStop_Click(object sender, RoutedEventArgs e) /*Stop button*/
        {
            if (server.IsStarted)
                server.Stop();

        }



    }
}







// Front end
<Window x:Class="PingServerApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PingServerApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Name="btn1" Content="Start" Click="OnClick1" ClickMode="Press" HorizontalAlignment="Left" Margin="418,10,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.517,0.658" Height="55" Width="385" Background="Gold"/>
        <Button Name="btn2" Content="Stop" Click="OnClick2" ClickMode="Press" HorizontalAlignment="Left" Margin="418,70,0,0" VerticalAlignment="Top" Width="390" Height="55" Background="Aqua"/>
        <DataGrid x:Name="dataGrid" ItemsSource="{Binding TCPConnectionModel}" Margin="0,0,387,10">
            <DataGrid.Columns>
                <DataGridTextColumn Header = "Started" Binding = "{Binding Started}"/>
                <DataGridTextColumn Header = "Processed" Binding = "{Binding Processed}" />
                <DataGridTextColumn Header = "Elapsed?" Binding = "{Binding Elapsed}" />
            </DataGrid.Columns>
        </DataGrid>
        <StatusBar Margin="413,293,5,10">
            <StatusBarItem Width="380" Height="69" VerticalAlignment="Bottom" RenderTransformOrigin="0.486,0.619" Margin="0,0,0,21">
                <TextBlock Text="Nothing yet" x:Name="resultveiw"></TextBlock>
            </StatusBarItem>
        </StatusBar>
    </Grid>
</Window>


// Front end test xaml
<Window x:Class="GUI.EchoWindowTest"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:GUI"
        mc:Ignorable="d"
        Title="EchoWindowTest" Height="450" Width="800">
    <Grid>

        <Grid.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FF39494C" Offset="0.008"/>
                <GradientStop Color="#FF39494C" Offset="1"/>
            </LinearGradientBrush>
        </Grid.Background>
        <Label Content="Host:" HorizontalAlignment="Left" Height="32" Margin="204,94,0,0" VerticalAlignment="Top" Width="62" FontSize="20" Foreground="White"/>
        <Label Content="Port:" HorizontalAlignment="Left" Margin="366,94,0,0" VerticalAlignment="Top" Height="40" Width="56" FontSize="20" Foreground="White"/>
        <DataGrid x:Name="dataGrid" ItemsSource="{Binding displayDataList}" Margin="0,0,617,0" Background="#FFDDDDDD">
            <DataGrid.Columns>
                <DataGridTextColumn Header = "Started" Binding = "{Binding Started}" />
                <DataGridTextColumn Header = "Processed" Binding = "{Binding Processed}" />
                <DataGridTextColumn Header = "Elapsed?" Binding = "{Binding Elapsed}" />
            </DataGrid.Columns>
        </DataGrid>
        <Button x:Name="btnStart" Content="Start" HorizontalAlignment="Left" Height="29" Margin="524,97,0,0" VerticalAlignment="Top" Width="97" Click="btnStart_Click"/>
        <Button x:Name="btnStop" Content="Stop" HorizontalAlignment="Left" Height="29" Margin="651,97,0,0" VerticalAlignment="Top" Width="95" Click="btnStop_Click"/>
        <TextBox x:Name="txtStatus" HorizontalAlignment="Left" Height="159" Margin="204,169,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="542" Background="#FFDDDDDD"/>
        <TextBox x:Name="txtHost" HorizontalAlignment="Left" Height="26" Margin="262,100,0,0" TextWrapping="Wrap" Text="127.0.0.1" VerticalAlignment="Top" Width="90" FontSize="20" Background="{x:Null}" Foreground="White"/>
        <TextBox x:Name="txtPort" HorizontalAlignment="Left" Height="26" Margin="418,99,0,0" TextWrapping="Wrap" Text="12345" VerticalAlignment="Top" Width="90" FontSize="20" Background="{x:Null}" Foreground="White"/>

    </Grid>
</Window>
Posted
Updated 20-Sep-22 14:37pm
v2
Comments
Richard MacCutchan 16-Sep-22 11:13am    
You need a server listening on port 12345.
Gcobani Mkontwana 19-Sep-22 4:45am    
@Richard MacCutchan can you help me how to do that based on what i have currently?
Gcobani Mkontwana 20-Sep-22 20:21pm    
@Richard MacCuthan, yes i do have server but how do i make it to inherit the TCPClient to have relationship with Server?
Richard MacCutchan 21-Sep-22 4:02am    
Sorry I do not understand. The server needs to be actively listening on a fixed port for connection requests. The client must try to connect to the listening port.
Gcobani Mkontwana 21-Sep-22 8:52am    
@Richard MacCutchan i guess i will research and keep on trying, hopefully i wont be stuck

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900