简体   繁体   English

使用C#模拟TCP / IP连接

[英]Mocking a TCP/IP connection with C#

I'm a bit of a network n00b, so please be gentle and explain things in a really, REALLY dummy way (it seems to me that every time it comes to network related stuff, people start talking a totally different language). 我是一个网络n00b,所以请温柔并以一种真正的,真正的虚拟方式解释事物(在我看来,每次涉及网络相关的东西,人们开始说一种完全不同的语言)。 I'm a fairly experienced C# programmer, but lacks some skill when it comes to communication between machines. 我是一个相当有经验的C#程序员,但在机器之间的通信方面缺乏一些技巧。

The scenario is this: I'm working with a product that communicates with other devices through tcp/ip. 场景是这样的:我正在使用通过tcp / ip与其他设备通信的产品。 Is it possible to make a dummy program that acts like ta tcp/ip connection (locally on my machine), so I can hook up my other program to it by setting its IP address (and port), and then have it return whatever mocking/testing data I want? 是否有可能制作一个像ta tcp / ip连接一样的虚拟程序(在我的机器上本地),所以我可以通过设置其IP地址(和端口)来连接我的其他程序,然后让它返回任何模拟/我想要的测试数据?

Yes: you can setup a TCP connection to a program running on your own machine. 是:您可以设置与自己计算机上运行的程序的TCP连接。 The host name you should use is localhost , or the IP address is 127.0.0.1 : see also Loopback (Virtual Network Interface) . 您应使用的主机名是localhost ,或IP地址是127.0.0.1 :另请参阅Loopback(虚拟网络接口)

Yep, entirely possible. 是的,完全可能。 Take a look at the System.Net.Sockets.TcpClient and System.Net.Sockets.TcpListener classes - they should be a good starting point. 看一下System.Net.Sockets.TcpClientSystem.Net.Sockets.TcpListener类 - 它们应该是一个很好的起点。

To be honest I don't see the point of 'mocking' anything here just use the proper TCP/IP connection, because obviously you can send the data over TCP/IP between 2 different applications on the same IP. 老实说,我没有看到“嘲笑”任何东西只是使用正确的TCP / IP连接,因为显然你可以通过TCP / IP在同一IP上的两个不同的应用程序之间发送数据。

Check out this example: 看看这个例子:

http://www.codeproject.com/KB/IP/tcpclientserver.aspx http://www.codeproject.com/KB/IP/tcpclientserver.aspx

I have done this before. 我之前做过这个。 I have created a set of tools for Mocking various technologies that you can download at: 我已经创建了一组用于模拟各种技术的工具,您可以从以下位置下载:

http://www.codeproject.com/KB/biztalk/Excellence.aspx http://www.codeproject.com/KB/biztalk/Excellence.aspx

This allows you to setup a data to be sent and received. 这允许您设置要发送和接收的数据。 You might have to tweak it a bit but main stuff is already there. 你可能需要调整一下,但主要的东西已经存在。

I believe you are interested in TcpReceiveMiniServer . 我相信你对TcpReceiveMiniServer很感兴趣。

Here is a mini-sample: 这是一个迷你样本:

    static void Main(string[] args)
    {
        TcpReceiveMiniServer server = new TcpReceiveMiniServer(8789);
        server.Start();
        server.DataArrived += new TcpReceiveMiniServer.DataArrivedHandler(server_DataArrived);
        Console.Read();
    }

    static void server_DataArrived(object sender, DataArrivedEventArgs e)
    {
        // do something with e.Data
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM