Stream.write()每个方法只能运行一次

时间:2015-01-11 21:54:47

标签: c# sockets

我有一个向客户端发送消息的方法,如下所示。但是,如果我一次又一次地调用这个方法两次它将无法正常工作,并且数据似乎从未发送过。

我在下面添加了一些评论来说明问题。

public static void SendRequestInformation(Client target, int messageId)
    {
        NetworkStream stream = target.getClientSocket().GetStream();
        byte[] byteData = null;
        switch (messageId)
        {
            case 0:
                byteData = Encoding.ASCII.GetBytes("ping");
                break;
            case 1:
                byteData = Encoding.ASCII.GetBytes("handshake");
                break; 
            case 3:
                byteData = Encoding.ASCII.GetBytes("osif");
                break;
            case 4:
                byteData = Encoding.ASCII.GetBytes("idle");
                break;
        }
        try
        {
            stream.Write(byteData, 0, byteData.Length);
            stream.Flush();
        }
        catch (Exception e)
        {
            ClientHandle.RemoveFromClientPool(target, "Unable to reach Client"); 
        }
    }

// so if here I have a method like...
private void onRefreshMenuClick(object sender, RoutedEventArgs e)
    {
        MenuItem mi = sender as MenuItem;
        if (mi != null)
        {
            ContextMenu cm = mi.CommandParameter as ContextMenu;
            if (cm != null)
            {
                Grid g = cm.PlacementTarget as Grid;
                if (g != null)
                {

                    var p = Mouse.GetPosition(g);

                    int row = 0;
                    int col = 0;
                    double accumulatedHeight = 0.0;
                    double accumulatedWidth = 0.0;

                    // calc row mouse was over
                    foreach (var rowDefinition in g.RowDefinitions)
                    {
                        accumulatedHeight += rowDefinition.ActualHeight;
                        if (accumulatedHeight >= p.Y)
                            break;
                        row++;
                    }
                    Client c = getRowClient(row);
                    if (c != null)
                    {
//the below two lines seem to not be called if called only the top one seems to work 
                        ConnectionHandle.SendRequestInformation(c, 1);
                        ConnectionHandle.SendRequestInformation(c, 4);
                    }
                    else
                        if (debugWindow != null)
                            debugWindow.LogTextBox.AppendText("Unable to find client!");
                }
            }
        }
    }

0 个答案:

没有答案