套接字仅读取断点设置

时间:2015-07-21 21:45:49

标签: c# winforms sockets

我正在编写套接字侦听器并使用SocketTest对其进行测试,并且只在设置断点时才会读取。它连接或不连接断点。我试着在一段时间内加入一个睡眠(无限因为它在它自己的线程上)。

使用断点,它每次都能很好地工作,这让我认为它是某种时间或缓冲问题,我可以使用一些帮助查明原因。异常块是空的(我只是编写代码)并将被添加到,但它们没有捕获,所以它不是一个例外问题。这是代码:

public static void doSocket()
    {
        TcpListener serverSocket = new TcpListener(Globals.foxProAddress, Globals.foxProPort);
        TcpClient clientSocket = default(TcpClient);
        try
        {
            serverSocket.Start();
        }
        catch (Exception e) { }
        clientSocket = serverSocket.AcceptTcpClient();
        while (true)
        {
            try
            {
                NetworkStream networkStream = clientSocket.GetStream();
                byte[] bytesFrom = new byte[100025];
                networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                string dataFromFoxPro = System.Text.Encoding.ASCII.GetString(bytesFrom);
                if (!dataFromFoxPro.Equals(""))
                {
                    Payments.startTransaction(dataFromFoxPro);
                }
            }
            catch (Exception e) { }
        }
    }

2 个答案:

答案 0 :(得分:2)

检查Read() [MSDN]的返回值:

  

如果没有可用于读取的数据,则Read方法返回0.

设置断点后,数据更有可能同时到达。

您还应该将索引(0)和读取的字节数传递给GetString() [MSDN]

我还将clientSocket.GetStream();移到循环之外,只是为了向读者说明你想在整个循环期间保持流。否则有人会认为缺少Dispose(),这会破坏流。

答案 1 :(得分:1)

这是约翰加德纳建议的一个简单例子:

    public static void doSocket()
    {
        try
        {
            TcpListener serverSocket = new TcpListener(Globals.foxProAddress, Globals.foxProPort);
            serverSocket.Start();
            TcpClient clientSocket = serverSocket.AcceptTcpClient();

            NetworkStream networkStream = clientSocket.GetStream();
            int bytesRead;
            string buffer = "";
            byte[] bytesFrom = new byte[4096];

            while (true)
            {

                bytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                string dataFromFoxPro = System.Text.Encoding.ASCII.GetString(bytesFrom, 0, bytesRead);
                buffer = buffer + dataFromFoxPro;
                // look at buffer and see if it has one or more complete "messages":
                while (buffer.Contains("something")) // made up protocol
                {
                    string msg = buffer.Substring(0, buffer.IndexOf("something")); // extract the message <-- completely made up
                    buffer = buffer.Remove(0, msg.Length); // remove the msg from the beginning of the buffer <-- pseudo-code!
                    Payments.startTransaction(msg);
                }

            }
        }
        catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

这是非常粗糙的代码,只是为了概述代码的外观。