您能否将 Stream 对象传递给方法以写入该特定流?

Can you pass a Stream object to a method to write to that specific stream?

我目前有一个服务器和两个与之通信的客户端。每次客户端连接到服务器时,我将 Stream 实例作为值存储,将客户端 ID 作为键存储在并发字典中。

private static ConcurrentDictionary<string, NetworkStream> pumpIDAndStream = new ConcurrentDictionary<string, NetworkStream>();

//then later in the program

pumpIDAndStream.AddOrUpdate(clientID.ToString(), stream, (k, v) => stream);

然后我使用此方法尝试根据存储在字典中的流对象向特定客户端实例发送消息:

private void proceedPump(byte[] b_recievedLine)
{

    string s_messageBody = DESDecrypt(b_recievedLine, DCSP);
    string[] delim = { " " };
    string[] strings = s_messageBody.Split(delim, StringSplitOptions.RemoveEmptyEntries);


    NetworkStream pumpStream = pumpIDAndStream[(strings[0])]; //strings[0] is the specific client ID
    byte[] empty = System.Text.Encoding.ASCII.GetBytes(""); 

    pumpStream.Write(messageFormatting(empty, 0x14, DCSP), 0, empty.Length);
    pumpStream.Flush();

}

调试后,它确实到达了 pumpStream.Flush();,但在特定客户端上什么也没有。有什么指点吗?

你什么都没写。

empty 是一个空数组,您对 Write 的调用使用它的长度 (0) 作为要写入的字节数(参见 the docs -您将 count 指定为 0).

你可能想做这样的事情:

var bytesToWrite = messageFormatting(empty, 0x14, DCSP);
pumpStream.Write(bytesToWrite, 0, bytesToWrite.Length);