如何在c#中测试TcpListener的localhost和端口号

时间:2013-11-25 13:40:54

标签: c# localhost tcplistener

我在c#中有一个代码从tcp ipaddress和端口号读取数据,但我的问题是我没有任何测试平台用ipaddress和端口号来测试应用程序。我关心的是这有什么办法通过它我可以在本地环境中测试我的代码..

这是我的代码..

 public class Listener
{

    private TcpListener tcpListener;
    private Thread listenThread;
    // Set the TcpListener on port 8081.
    Int32 port = 8081;
    IPAddress localAddr = IPAddress.Parse("192.168.1.3");
    Byte[] bytes = new Byte[256];

    public void ListenForClients()
    {

        this.tcpListener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcpListener.AcceptTcpClient();

            //create a thread to handle communication 
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }
    public void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                //blocks until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                //a socket error has occured
                // System.Windows.MessageBox.Show("socket");
                break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                // System.Windows.MessageBox.Show("disc");
                break;
            }

            //message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();

            String textdata = encoder.GetString(message, 0, bytesRead);
            System.IO.File.AppendAllText(@"D:\ipdata.txt", textdata);


        }

        tcpClient.Close();
    }
}

请帮我解决这个问题.. 提前谢谢..

3 个答案:

答案 0 :(得分:0)

要测试TCP侦听应用程序,您显然需要编写TCP传输应用程序。你可以写下来:

  • 同时运行

OR

  • 在您的操作系统和虚拟机中的发射器上运行侦听器。我这样做了并且在俄语上写了一个post on my blog(来源也可以下载)。

答案 1 :(得分:0)

我认为您可以将侦听器配置为127.0.0.1并通过localhost connetcion测试逻辑,如果您有传输系统的一部分

答案 2 :(得分:0)

使用RESTClient chrome / firefox AddOn(http://restclient.net/)将数据发送到Intranet环境中的IP和端口,我用这个