我已经有了客户端A将文件发送到服务器的代码。现在如何使服务器将文件转发到客户端B?有人请帮助我,提供一些基本代码,它不一定完全正确,但是至少我要遵循一些规则。非常感谢
答案 0 :(得分:0)
小例子: 参数是您要作为Byte []发送的文件,以及一个将客户端名称和TcpClient作为值的字典。
在这种情况下,您可以将文件发送给所有客户端,但是当然您只能将其修改为仅一个客户端。
public static void SendBytesToClients(Byte[] broadcastBytes, Dictionary<string, TcpClient> receiverList)
{
foreach (var client in receiverList)
{
try
{
TcpClient broadcastSocket = (TcpClient)client.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
catch (Exception ex)
{
Console.WriteLine(ex);
ClientConnector.ClientsList.Remove(client.Key);
}
}
}
客户端收到如下消息:
private void GetMessage()
{
while (_clientSocket.Connected)
{
_serverStream = _clientSocket.GetStream();
byte[] inStream = new byte[_clientSocket.ReceiveBufferSize];
int buffSize = _clientSocket.ReceiveBufferSize;
_serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
if (returndata.StartsWith("$CodeStart"))
{
CompileCode("" + returndata.Replace("$CodeStart", string.Empty));
}
else
{
_readData = "" + returndata;
Msg();
}
}
}
根据您的问题,我认为您已经建立了网络流。
一个教程,确切解释了您想要做什么,请参见此处: http://csharp.net-informations.com/communications/csharp-chat-server-programming.htm