在应用程序之间发送信息 [英] Send information between applications

查看:66
本文介绍了在应用程序之间发送信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,



我有一个客户端应用程序,它向服务器发送客户端打开的应用程序列表。它特别发送文件路径,文件名和主机名。我的问题是,在服务器中接收到发送的数据后,应该对发送的数据进行序列化和反序列化。我是C#的新手,所以我对序列化几乎一无所知。



这是客户端

 私有列表< int> listingProcesses =新的List< int>(); 
private void SendData()
{
String processID =;
字符串processName =;
字符串processPath =;
字符串processFileName =;
字符串processMachinename =;

listBox1.BeginUpdate();
试试
{
piis = GetAllProcessInfos();
for(int i = 0; i< piis.Count; i ++)
{
尝试
{
if(!listedProcesses.Contains(piis [i] .Id))//将其放置在列表中以避免冗余
{
listingProcesses.Add(piis [i] .Id);
processID = piis [i] .Id.ToString();
processName = piis [i] .Name.ToString();
processPath = piis [i] .Path.ToString();
processFileName = piis [i] .FileName.ToString();
processMachinename = piis [i] .Machinename.ToString();
output.Text + = \nSENT DATA:\n\t + processFileName + \n\t + processMachinename + \n\t + processID + \n\t + processName + \n\t + processPath + \n;
}

}
捕获(例外)
{
wait.Abort();
output.Text + =错误..... + ex.StackTrace;

}

NetworkStream ns = tcpclnt.GetStream();
字符串数据=;
data =-++ + + processFileName + + processMachinename + + processID + + processPath;
if(ns.CanWrite)
{
byte [] bf = new ASCIIEncoding()。GetBytes(data);
ns.Write(bf,0,bf.Length);
ns.Flush();
}
}
}
最后
{
listBox1.EndUpdate();
}
}

private void cmd_dis_Click(对象发送者,EventArgs e)
{
if(wait!= null)
{
wait.Abort();
//read.Close(2000);
}

IPAddress ipclient = Dns.GetHostByName(Dns.GetHostName())。AddressList [0];
字符串ipclnt = + @@ + + ipclient.ToString();
NetworkStream ns = tcpclnt.GetStream();
if(ns.CanWrite)
{
byte [] bf = new ASCIIEncoding()。GetBytes(ipclnt);
ns.Write(bf,0,bf.Length);
ns.Flush();
}

tcpclnt.Close();
// read.Close();
Application.Exit();
}

private void listBox1_SelectedIndexChanged(对象发送方,EventArgs e)
{
ProcessInfoItem pii = piis.FirstOrDefault(x => x.Id ==(int )(发送者为ListBox).SelectedValue);
if(pii!= null)
{
字符串hostName = System.Net.Dns.GetHostName();

textBox4.Text = listBox1.SelectedValue.ToString();
textBox5.Text =(pii.FileName);
textBox6.Text =(pii.Path);
textBox7.Text =(pii。机器名称);
}
}

private List< ProcessInfoItem> piis = new List< ProcessInfoItem>();
private void Form1_Load(object sender,EventArgs e)
{
piis = GetAllProcessInfos();
listBox1.DisplayMember =名称;
listBox1.ValueMember = Id;
listBox1.DataSource = piis;

}
private List< ProcessInfoItem> GetAllProcessInfos()
{

List< ProcessInfoItem>结果=新List< ProcessInfoItem>();
Process currentProcess = Process.GetCurrentProcess();
Process []进程= Process.GetProcesses();
foreach(进程中的进程p)
{
if(!String.IsNullOrEmpty(p.MainWindowTitle))
{
// ProcessInfoItem pii = new ProcessInfoItem(p .Id,p.MainModule.ModuleName,p.MainModule.FileName,p.MainWindowTitle);
ProcessInfoItem pii =新的ProcessInfoItem(p.Id,p.MainModule.ModuleName,p.MainWindowTitle,p.MainModule.FileName,Environment.MachineName);
结果。添加(pii);
}
}
返回结果;
}
公共类ProcessInfoItem
{
public int Id {get;组; }
公共字符串Name {get;组; }
公用字串FileName {get;组; }
公用字串Path {get;组; }
公用字符串Machinename {get;组; }
public ProcessInfoItem(int id,字符串名称,字符串文件名,字符串路径,字符串机器名)
{
this.Id = id;
this.Name =名称;
this.FileName =文件名;
this.Path =路径;
this.Machinename =机器名;
}
}

这是需要反序列化的服务器

 私有无效recieveData()
{
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding ascii = null;
而(!stopRecieving)
{
if(nStream.CanRead)
{
byte [] buffer = new byte [1024];
nStream.Read(buffer,0,buffer.Length);
ascii = new ASCIIEncoding();
recvDt = ascii.GetString(buffer);
/ *接收到的消息检查它是否具有+ @@ +,则表明IP已断开连接* /
bool f = false;
f = recvDt.Contains( + @@ +);
如果(f)
{
字符串d = + @@ +;
recvDt = recvDt.TrimStart(d.ToCharArray());
clientDis();
stopRecieving = true;
}

//否则,如果(recvDt.Contains( ^^))
// {
//新的Transmit_File()。transfer_file(file, ipselected);
//}
/ * ++-shutdowns / restrt / logoff / abort * /
else if(recvDt.Contains( ++-))
{
string d = ++-;
recvDt = recvDt.TrimStart(d.ToCharArray());
this.Invoke(new rcvData(addToOutput));
clientDis();
}
/ *-++正常msg * /
否则,如果(recvDt.Contains(-++))
{

字符串d =-++;
recvDt = recvDt.TrimStart(d.ToCharArray());
this.Invoke(new rcvData(addToOutput));

}
}
Thread.Sleep(1000);
}

}


public void addToOutput()
{
if(recvDt!= null& recvDt!=)
{
output.Text + = \n收到的数据: + recvDt;
recvDt = null;



}

}

谢谢。

解决方案

您基本上需要


就是这么简单。您可以根据需要更改代码。


将复杂数据传递给服务的示例:

  [ DataContract] 
公共类MyMessageClass
{
[DataMember]
公共字符串MyValue1 {get; set;}

[DataMember]
公共字符串MyValue2 {get; set;}
}

然后,您可以更新界面和服务补充,只需使用它而无需序列化和反序列化任何东西,所有事情都将由WCF在后台完成。


请注意,您可以将WCF Services与Windows Forms Applications和Console Applications一起使用,并且可以继续按照您的方式开发项目。您唯一需要做的更改是向将在服务器上运行的应用程序中添加服务,然后在将在客户端上运行的应用程序中使用该服务。它与您的应用程序的逻辑无关。为了简单起见,我提供的示例位于控制台应用程序中。


Good day,

I have a client application which sends to the server a lists of application the client opens. It particulary sends the file path, file name and hostname. My problem is the sent data should be serialize and deserialize when it is received in the server. I am new to C# so I have very little idea of Serialization.

This is the client side

private List<int> listedProcesses = new List<int>();
        private void SendData()
        {
            String processID = "";
            String processName = "";
            String processPath = "";
            String processFileName = "";
            String processMachinename = "";

            listBox1.BeginUpdate();
            try
            {   
                piis = GetAllProcessInfos();
                for (int i = 0; i < piis.Count; i++)
                {
                    try
                    {
                        if (!listedProcesses.Contains(piis[i].Id)) //placed this on a list to avoid redundancy
                        {
                            listedProcesses.Add(piis[i].Id);
                            processID = piis[i].Id.ToString();
                            processName = piis[i].Name.ToString();
                            processPath = piis[i].Path.ToString();
                            processFileName = piis[i].FileName.ToString();
                            processMachinename = piis[i].Machinename.ToString();
                            output.Text += "\n\nSENT DATA : \n\t" + processFileName + "\n\t" + processMachinename + "\n\t" + processID + "\n\t" + processName + "\n\t" + processPath + "\n";
                        }

                    }
                    catch (Exception ex)
                    {
                        wait.Abort();
                        output.Text += "Error..... " + ex.StackTrace;

                    }

                    NetworkStream ns = tcpclnt.GetStream();
                    String data = "";
                    data = "--++" + "  " + processFileName + " " + processMachinename + " " + processID + " " + processPath;
                    if (ns.CanWrite)
                    {
                        byte[] bf = new ASCIIEncoding().GetBytes(data);
                        ns.Write(bf, 0, bf.Length);
                        ns.Flush();
                    }
                }
            }
            finally
            {
                listBox1.EndUpdate();
            } 
        }

        private void cmd_dis_Click(object sender, EventArgs e)
        {
            if (wait != null)
            {
                wait.Abort();
                //read.Close(2000);
            }

            IPAddress ipclient = Dns.GetHostByName(Dns.GetHostName()).AddressList[0];
            String ipclnt = "+@@+" + ipclient.ToString();
            NetworkStream ns = tcpclnt.GetStream();
            if (ns.CanWrite)
            {
                byte[] bf = new ASCIIEncoding().GetBytes(ipclnt);
                ns.Write(bf, 0, bf.Length);
                ns.Flush();
            }

            tcpclnt.Close();
           // read.Close();
            Application.Exit();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ProcessInfoItem pii = piis.FirstOrDefault(x => x.Id == (int)(sender as ListBox).SelectedValue);
            if (pii != null)
            {
                string hostName = System.Net.Dns.GetHostName();

                textBox4.Text = listBox1.SelectedValue.ToString();
                textBox5.Text = (pii.FileName);
                textBox6.Text = (pii.Path);
                textBox7.Text = (pii.Machinename);
            }
        }

        private List<ProcessInfoItem> piis = new List<ProcessInfoItem>();
        private void Form1_Load(object sender, EventArgs e)
        {
            piis = GetAllProcessInfos();
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "Id";
            listBox1.DataSource = piis;

        }
        private List<ProcessInfoItem> GetAllProcessInfos()
        {

            List<ProcessInfoItem> result = new List<ProcessInfoItem>();
            Process currentProcess = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcesses();
            foreach (Process p in processes)
            {
                if (!String.IsNullOrEmpty(p.MainWindowTitle))
                {
                    //ProcessInfoItem pii = new ProcessInfoItem(p.Id, p.MainModule.ModuleName, p.MainModule.FileName, p.MainWindowTitle);
                    ProcessInfoItem pii = new ProcessInfoItem(p.Id, p.MainModule.ModuleName, p.MainWindowTitle, p.MainModule.FileName, Environment.MachineName);
                    result.Add(pii);
                }
            }
            return result;
        }
        public class ProcessInfoItem
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string FileName { get; set; }
            public string Path { get; set; }
            public string Machinename { get; set; }
            public ProcessInfoItem(int id, string name, string filename, string path, string machinename)
            {
                this.Id = id;
                this.Name = name;
                this.FileName = filename;
                this.Path = path;
                this.Machinename = machinename;
            }
        }

and here is the server which needs to be deserialize

  private void recieveData()
        {
            NetworkStream nStream = tcpClient.GetStream();
            ASCIIEncoding ascii = null;
            while (!stopRecieving)
            {
                if (nStream.CanRead)
                {
                    byte[] buffer = new byte[1024];
                    nStream.Read(buffer, 0, buffer.Length);
                    ascii = new ASCIIEncoding();
                    recvDt = ascii.GetString(buffer);
                    /*Received message checks if it has +@@+ then the ip is disconnected*/
                    bool f = false;
                    f = recvDt.Contains("+@@+");
                    if (f)
                    {
                        string d = "+@@+";
                        recvDt = recvDt.TrimStart(d.ToCharArray());
                        clientDis();
                        stopRecieving = true;
                    }

                    //else if (recvDt.Contains("^^"))
                    //{
                    //    new Transmit_File().transfer_file(file, ipselected);
                    //}
                    /* ++-- shutsdown/restrt/logoff/abort*/
                    else if (recvDt.Contains("++--"))
                    {
                        string d = "++--";
                        recvDt = recvDt.TrimStart(d.ToCharArray());
                        this.Invoke(new rcvData(addToOutput));
                        clientDis();
                    } 
                    /*--++ Normal msg*/
                    else if (recvDt.Contains("--++"))
                    {

                        string d = "--++";
                        recvDt = recvDt.TrimStart(d.ToCharArray());
                        this.Invoke(new rcvData(addToOutput));

                    }
                }
                Thread.Sleep(1000);
            }

        }


public void addToOutput()
        {
            if (recvDt != null && recvDt != "")
            {
                output.Text += "\n Received Data : " + recvDt;
                recvDt = null;



            }

        }

Thank you.

解决方案

You basically need Interprocess Communication.

As an option you can use WCF for communication between your client and server application.

You can create a service and host it in an application that will be receive data from other application and consume service in other application to send data and show response.

Here is an example of the doing it in a simple way. In this sample I have created 2 applications. Application2 Sends a data to Application1 automatically once in each 10 secconds and Application1 sends a response back to Application2 and Application2 will show response.

To run sample codes follow this steps:

  1. Create a soloution with 2 console applications, Application1 and Application2
  2. Add System.ServiceModel reference to both projects.
  3. Paste below codes in program.cs of each project.
  4. Right click on solution and in Properties, make solution Multi startup projects and set Action of each project 'Start'
  5. Press Ctrl+F5 to run projects
  6. In Application1 window you will see a service is running message.
  7. Application2 will send DateTime.Now to Application 2 every 10 secconds and will receive a respone from Application 2 and display it it Application1 Window.

Application1 Program.cs

using System;
using System.ServiceModel;

namespace Application1
{
    [ServiceContract]
    public interface IEchoService
    {
        [OperationContract]
        string Echo(string value);
    }

    public class EchoService : IEchoService
    {
        public string Echo(string value)
        {
            return string.Format("You send me data'{0}'", value);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(EchoService), new Uri[] { new Uri("http://localhost:8000") }))
            {
                host.AddServiceEndpoint(typeof(IEchoService), new BasicHttpBinding(), "Echo");
                host.Open();
                Console.WriteLine("Service is running...");
                Console.WriteLine("Press Enter to exit if you want to close service.");
                Console.ReadLine();
                host.Close();
            }
        }
    }
}

Application2 Program.cs

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Application2
{
    [ServiceContract]
    public interface IEchoService
    {
        [OperationContract]
        string Echo(string value);
    }

    class Program
    {
        static void Main(string[] args)
        {
            //In real implementation, use server IP instead of localhost
            ChannelFactory<IEchoService> factory = new ChannelFactory<IEchoService>(new BasicHttpBinding(), new EndpointAddress("http://localhost:8000/Echo"));
            IEchoService proxy = factory.CreateChannel();
            int processedSeccond = 0;
            while (true)
            {
                var dateTime = DateTime.Now;
                if (dateTime.Second % 10 == 0 && dateTime.Second!=processedSeccond)
                {
                    processedSeccond = dateTime.Second;
                    string data= dateTime.ToString(); //or Console readLine for manual data entry
                    Console.WriteLine("Recieved Response: " + proxy.Echo(str));
                }
            }
        }
    }
}

Result

It's that simple. You can change codes to your desire.

An an example of passing complex data to service:

[DataContract]
public class MyMessageClass
{
    [DataMember]
    public string MyValue1 {get;set;}

    [DataMember]
    public string MyValue2 {get;set;}
}

Then you can update the interface and inplementation of service and simply use it without need to serialize and deserialize anything, all things will be done by WCF behind the scene.

Pleae note you can use WCF Services with both Windows Forms Applications and Console Applications and you can continue to develop your project the same way you are doing. The only change you need is to add a service to the application that will run on server and then consume that service in application that will run on client. It is not related to logic of your application all. And the samples that I provided is in Console Application just for sake of simplicity.

这篇关于在应用程序之间发送信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆