Home>

We become indebted to.
I'm sorry, socket communication, C # and Visual Studio are amateurs, but please give me some advice.

I would like to try socket communication like the site below.
However, since there is only one PC and it is not high spec enough to put in a virtual PC, I sent the data to myself and
I would like to create a program that makes communication simple by myself.

■ Referenced sites
I made an asynchronous inter-app communication app with WPF

However, at the moment I get the following error:

■ Error details
error CS0111: Type'MainWindow'already defines a member called'.ctor' with the same parameter type.

Is there any way to eliminate this error and perform socket communication on a single PC?
If socket communication is possible, we are thinking of creating new logic.
If i understand, please give me some advice.

<Window x: Class = "WpfApp4.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: WpfApp4"
        mc: Ignorable = "d"
        Title = "Client" Height = "160" Width = "240"><Grid>    <TextBox VerticalContentAlignment = "Center"
                 HorizontalContentAlignment = "Center"
                 HorizontalAlignment = "Left"
                 VerticalAlignment = "Top"
                 Height = "115"
                 Width = "243"
                 FontSize = "48"
                 Text = "{Binding Value, UpdateSourceTrigger = PropertyChanged}" />    <!-Text is bound to the Value property, so if you change the value in the textbox
             The corresponding Value property is changed.
             UpdateSourceTrigger is PropertyChanged.
             By doing this, it will be updated when the value is entered, and the value can be sent to the Client side in real time->    <TextBox x: Name = "value" VerticalContentAlignment = "Center" HorizontalContentAlignment = "Center" HorizontalAlignment = "Left" Height = "127" TextWrapping = "Wrap" VerticalAlignment = "Top" Width = "229" FontSize = "48" Text = "{Binding Value}" Margin = "325,0,0,0" /></Grid></Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.ComponentModel;
namespace WpfApp4
{
    ///<summary>  /// Interaction logic for MainWindow.xaml
    ///</summary>  public partial class MainWindow: Window
    {
        public MainWindow ()
        {
            InitializeComponent ();
            /// If i set ServerValue in the data context
            /// Binding ServerValue property on XAML side
            /// become able to. The binding is simply
            /// Values ​​can be linked between the UI and the object
            /// This time, link the Value property to the text box
            Since /// is linked, in the text box
            /// When you change the value, the Value property also changes.
            this.DataContext = new ServerValue ();
        }
    }
}
public class ServerValue: INotifyPropertyChanged{
    public event PropertyChangedEventHandler PropertyChanged;
    #region property
    ///<summary>  /// Data part exchanged by communication this time
    /// Have Getter/Setter
    /// By using OnPropertyChanged in Setter
    /// A change notification is sent to the UI and the UI value is updated
    /// In this example, Server doesn't make much sense again
    ///</summary>  private int _value;
    public int Value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
            OnPropertyChanged ("Value");
        }
    }
    #endregion
    #region constructor
    public ServerValue ()
    {
        Value = 0;
        var ipAdd = System.Net.Dns.GetHostEntry ("localhost"). AddressList [0];
        listener = new System.Net.Sockets.TcpListener (System.Net.IPAddress.Any, 12301);
        listener.Start ();
        accept ();
    }
    #endregion
    ///<summary>  /// Accept TCP Client connection request
    /// Wait asynchronously until accepted
    /// If accepted, pass the process to acceptClient
    ///</summary>  async void accept ()
    {
        while (true)
        {
            var client = await listener.AcceptTcpClientAsync ();
            acceptClient (client);
        }
    }
    ///<summary>  /// For clients with a probable connection
    /// Wait asynchronously for a request. When a request comes
    /// Respond to the request.
    /// After responding, wait until the request comes again.
    ///</summary>  ///<param name = "client"></param>  async void acceptClient (System.Net.Sockets.TcpClient client)
    {
        var ns = client.GetStream ();
        // Prepare a box to receive received data
        byte [] result_byte = new byte [256];
        do
        {
            // Wait until data is taken from the network stream
            int result_size = await ns.ReadAsync (result_byte, 0, result_byte.Length);
            // If the size is 0, it is judged that the connection has been disconnected and the client is closed.
            // Wait until the connection comes again in the upper layer
            if (result_size == 0)
            {
                client.Close ();
                return;
            }
            // Judges that something has been received and returns the value of the Value property as a string
            var enc = System.Text.Encoding.UTF8;
            var send_bytes = enc.GetBytes (Value.ToString ());// Pack the data in a box for sending
            ns.Write (send_bytes, 0, send_bytes.Length);} while (ns.DataAvailable);
        // Recursive call to wait for reception again
        acceptClient (client);
    }
    private System.Net.Sockets.TcpListener listener;
    ///<summary>  /// A method to tell the UI that the value has been updated
    /// Tells that the property specified by name has been updated.
    ///</summary>  ///<param name = "name"></param>  private void OnPropertyChanged (string name)
    {
        if (PropertyChanged! = Null)
        {
            PropertyChanged (this, new PropertyChangedEventArgs (name));
        }
    }
}
namespace AppsCommunicationClient
{
    public partial class MainWindow: Window
    {
        public MainWindow ()
        {
            this.DataContext = new Client ();
        }
    }
    public class Client: INotifyPropertyChanged
    {
        public System.Net.Sockets.NetworkStream Stream {get;set;}
        private int _value;
        public int Value
        {
            get
            {
                return _value;
            }
            set
            {
                _value = value;
                OnPropertyChanged ("Value");
            }
        }
        public Client ()
        {
            var _client = new System.Net.Sockets.TcpClient ("localhost", 12301);
            Stream = _client.GetStream ();
            this.Value = 0;
            read_value ();
        }
        ~ Client ()
        {
            Stream.Close ();
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged (string name)
        {
            if (PropertyChanged! = Null)
            {
                PropertyChanged (this, new PropertyChangedEventArgs (name));
            }
        }
        async void read_value ()
        {
            var enc = System.Text.Encoding.UTF8;
            var send_bytes = enc.GetBytes ("read");// Currently send any character
            byte [] result_byte = new byte [256];
            Stream.Write (send_bytes, 0, send_bytes.Length);
            await Stream.ReadAsync (result_byte, 0, result_byte.Length);
            Value = int.Parse (enc.GetString (result_byte));
            read_value ();
        }
    }
}
  • Answer # 1

    If socket communication is possible, we are thinking of creating new logic.

    The article on the site that the questioner referred to contains various elements such as "socket (TCP client, server) communication", "asynchronous", "WPF", "data binding", etc., so I admit that I am a beginner in C #. To be honest, I wouldn't recommend it if it is done.

    Refer to the following articles,
    .NET Network Programming Socket Code Example-Microsoft Docs

    We strongly recommend that you understand them one by one. Regarding socket communication, don't worry because both client and server programs run on one PC at the same time. (It is equivalent to launching a WEB server such as IIS or Apache on your own PC and accessing it from your own PC with a WEB browser)

    If you want to create something like a referenced site program yourself, but want to understand it step by step:

    Create and understand a program that performs socket communication, a TCP client, and a server.

    Create and understand desktop window programs in WPF.
    * WPF data binding is not directly related to socket communication

    Try synchronous socket communication in a WPF window to understand what happens when it's not asynchronous.
    * Asynchronous programming is blocked by synchronous communication, and if there is a UI, the operation will not get stuck, but perhaps at first, what is happening even if you look at the code or write it? It's hard to understand

    I think it is better to go in the order like.