using System; using System.Collections.Generic; //using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using LYFZ.Network.EnumerateLibrary; namespace LYFZ.Network { /* /// /// 远程数据处理类 主动模式 /// public class TCP_RemoteDataHandler { private TcpClient client; public TcpClient Client { get { return client; } set { client = value; } } /// /// 来至远程的网络数据流 /// private NetworkStream streamToClient; /// /// 来至远程的网络数据流 /// public NetworkStream StreamToClient { get { return streamToClient; } set { streamToClient = value; } } /// /// 缓冲字节大小 /// private const int bufferSize = 8192; /// /// 缓冲字节大小 /// public int BufferSize { get { return bufferSize; } } /// /// 缓冲字节数组 /// private byte[] buffer; /// /// 缓冲字节数组 /// public byte[] Buffer { get { return buffer; } set { buffer = value; } } /// /// 协议处理对象 /// private TCP_ProtocolHandler handler; /// /// 协议处理对象 /// public TCP_ProtocolHandler Handler { get { return handler; } set { handler = value; } } /// /// 初始化 /// /// public TCP_RemoteDataHandler(TcpClient client) { this.client = client; // 获得流 streamToClient = client.GetStream(); buffer = new byte[BufferSize]; handler = new TCP_ProtocolHandler(); } /// /// 读取信息 /// /// /// public TCP_FileProtocol ReadFileProtocol(NetworkStream stream) { int bytesRead=0; byte[] TempBuffer = new byte[BufferSize]; // 清空缓存,避免脏读 string[] protocolArray = null; try { bytesRead = stream.Read(TempBuffer, 0, BufferSize); if (bytesRead > 0) { string msg = Encoding.Unicode.GetString(TempBuffer, 0, bytesRead); protocolArray = handler.GetProtocol(msg);//获取完整的协议信息 } } catch { LYFZ.BLL.BLL_FileLogs.WriteMainLogs("服务器端已经断开连接..."); } TCP_FileProtocol protocol = new TCP_FileProtocol(); if (protocolArray.Length > 0) { TCP_ProtocolHelperXML helper = new TCP_ProtocolHelperXML(protocolArray[0]); protocol = helper.GetProtocol(); } return protocol; } #region 服务器端创建客户端连接 /// /// 创建客户端连接 /// public void CreateClientConnection() { // 打印连接到的客户端信息 // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("已收到连接请求:本地终结点 {0} <--收到-- 远程客户终结点 {1} 的连接请求,正在建立连接...", client.Client.LocalEndPoint, client.Client.RemoteEndPoint)); try { TCP_FileProtocol protocol = ReadFileProtocol(StreamToClient); if (protocol.InfoType == InformationType.Message) { OnCreateClientConnection(protocol); } if (streamToClient != null) { streamToClient.Dispose(); } client.Close(); } catch (Exception ex) { if (streamToClient != null) { streamToClient.Dispose(); } client.Close(); LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("错误:{0}", ex.Message)); } } /// /// 创建客户端连接 /// private void OnCreateClientConnection(TCP_FileProtocol protocol) { if (protocol.Content.Trim().ToLower() == "Connect".ToLower()) { try { // 获取网络端点表示的 IP 地址和端口号 IPEndPoint endPoint = client.Client.RemoteEndPoint as IPEndPoint; string thisClientIPAddrss = endPoint.Address.ToString(); //client.Client.RemoteEndPoint.ToString().Split(':')[0]; // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("开始与远程客户端建立连接:远程客户IP {0} 和端口 {1},正在建立连接...", thisClientIPAddrss, protocol.ClientPort)); // ServerToClientConnectionStart(thisClientIPAddrss, protocol.ClientPort);//创建服务器到客户端的连接 } catch (Exception ex) { LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("错误:{0}", ex.Message)); } } } /// /// 创建服务器到客户端的连接 /// /// protected void ServerToClientConnectionStart(string hostOrIP, int port) { TcpClient ServerToClientent = new TcpClient(); System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(hostOrIP); // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("正在连接{0}:{1} 客户端...", hostOrIP, port)); ServerToClientent.Connect(ipaddress, port); // 与服务器连接 try { if (ServerToClientent.Connected) { // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("服务器已成功与{0}:{1} 客户端,建立TCP连接...", hostOrIP, port)); Thread t = new Thread(new ThreadStart(delegate() { TCP_RemoteDataHandler wapper = new TCP_RemoteDataHandler(ServerToClientent); wapper.BeginRead(); })); t.IsBackground = true; t.Start(); } else { LYFZ.BLL.BLL_FileLogs.WriteMainLogs("连接失败,请检查网络环境是否正常..."); } } catch(Exception ex) { LYFZ.BLL.BLL_FileLogs.WriteMainLogs("连接错误:"+ex.Message+",请检查网络环境是否正常..."); } } #endregion 服务器端创建客户端连接 -- END #region 客户端处理来至服务器的连接 /// /// 客户端处理方法 /// public void ClientConnectionProcess() { try { TCP_FileProtocol protocol = ReadFileProtocol(StreamToClient); if (protocol.InfoType == InformationType.Message) { if (protocol.Content == "ConnectClient") { LYFZ.BLL.BLL_FileLogs.WriteMainLogs("服务已授理连接请求,并连接成功."); } } else { if (streamToClient != null) { streamToClient.Dispose(); } client.Close(); } } catch (Exception ex) { if (streamToClient != null) { streamToClient.Dispose(); } client.Close(); LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("错误:{0}", ex.Message)); } } #endregion */ #region 客户端发送指令到服务端处理方法 /* /// /// 发送指令到服务端并返回服务器的处理结果 /// /// 要发送到服务器的指令 /// 发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔 /// public string SendCommandToServer(TransferCommand command = TransferCommand.Message, string msgOrParameters = "Hello", string fileName = "", int port = 8500, LYFZ.Network.EnumerateLibrary.InformationType type = LYFZ.Network.EnumerateLibrary.InformationType.Message) { string tempMsg = ""; LYFZ.Network.TCP_FileProtocol msgXML = new Network.TCP_FileProtocol(type, msgOrParameters); string sendMsg = msgXML.ToString(); byte[] tempSendBuffer = Encoding.Unicode.GetBytes(sendMsg); // 获得缓存 try { lock (StreamToClient) { StreamToClient.Write(tempSendBuffer, 0, tempSendBuffer.Length); // 将连接请求发往服务器 } TCP_FileProtocol protocol = ReadFileProtocol(StreamToClient); if (protocol.InfoType == InformationType.Message) { tempMsg = protocol.Content; } } catch { LYFZ.BLL.BLL_FileLogs.WriteMainLogs("连接已断开,请检查网络环境是否正常..."); } return tempMsg; }*/ #endregion #region 服务器接收并处理客户端请求 /* /// /// 服务器开始进行异步读取 /// public void BeginRead() { AsyncCallback callBack = new AsyncCallback(OnReadComplete); streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null); } /// /// 再读取完成时进行回调 /// /// private void OnReadComplete(IAsyncResult ar) { int bytesRead = 0; if (Client.Connected) { try { lock (streamToClient) { try { bytesRead = streamToClient.EndRead(ar); } catch { bytesRead = 0; } } if (bytesRead == 0) { LYFZ.BLL.BLL_FileLogs.WriteMainLogs(("客户端>" + client.Client.RemoteEndPoint + "已断开连接,读取到0字节")); } else { string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Array.Clear(buffer, 0, buffer.Length); // 清空缓存,避免脏读 // 获取protocol数组 try { string[] protocolArray = handler.GetProtocol(msg);//获取完整的协议信息 foreach (string pro in protocolArray) { // 这里异步调用,不然这里可能会比较耗时 ParameterizedThreadStart start = new ParameterizedThreadStart(handleProtocol); start.BeginInvoke(pro, null, null); } } catch { } // 再次调用BeginRead(),完成时调用自身,形成无限循环 lock (streamToClient) { AsyncCallback callBack = new AsyncCallback(OnReadComplete); streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null); } } } catch (Exception ex) { if (streamToClient != null) { streamToClient.Dispose(); } client.Close(); LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("错误:{0}", ex.Message)); ClientDisconnected(); } } else { // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("客户端>" + client.Client.RemoteEndPoint + "已主动断开连接。")); ClientDisconnected(); } } /// /// 当客户端连接断开时执行方法 /// private void ClientDisconnected() { //根据实际需要实现相应功能 LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("客户端连接断开时执行结果:{0}", "暂无处理!")); } /// /// 向当前网络流写入数据 /// /// public void StreamWrite(string value) { byte[] temp = Encoding.Unicode.GetBytes(value); // 获得缓存 try { lock (StreamToClient) { StreamToClient.Write(temp, 0, temp.Length); // 将连接请求发往服务器 } } catch { } } /// /// 服务器读取到端客户端数据后的处理程序protocol /// /// private void handleProtocol(object obj) { string pro = obj as string; TCP_ProtocolHelperXML helper = new TCP_ProtocolHelperXML(pro); TCP_FileProtocol protocol = helper.GetProtocol(); if (protocol.InfoType == InformationType.Message) { TCP_FileProtocol returnProtocol = new Network.TCP_FileProtocol(LYFZ.Network.EnumerateLibrary.InformationType.Message, "服务器已接收到:" + protocol.Content + "..."); StreamWrite(returnProtocol.ToString()); } else if (protocol.InfoType == InformationType.File) { TCP_FileProtocol returnProtocol = TransmissionFileHandling(protocol); StreamWrite(returnProtocol.ToString()); } } /// /// 文件传输处理方法 /// /// /// private TCP_FileProtocol TransmissionFileHandling(TCP_FileProtocol protocol) { TCP_FileProtocol returnProtocol = new TCP_FileProtocol(); string Command = protocol.Command.ToString(); string[] GetParameters = protocol.Content.Split('|'); string AvatarSaveFilePath = LYFZ.WinAPI.CustomPublicMethod.BasePath; switch (Command.ToLower()) { case "uploadavatar": AvatarSaveFilePath = LYFZ.WinAPI.CustomPublicMethod.BasePath + "\\Resources\\Avatar\\User\\" + protocol.FileName; if (receiveFile(protocol, AvatarSaveFilePath)) { returnProtocol = new Network.TCP_FileProtocol(LYFZ.Network.EnumerateLibrary.InformationType.Message, "头像上传成功"); } else { returnProtocol = new Network.TCP_FileProtocol(LYFZ.Network.EnumerateLibrary.InformationType.Message, "头像上传失败!"); } break; case "downloadavatar": AvatarSaveFilePath = LYFZ.WinAPI.CustomPublicMethod.BasePath + "\\Resources\\Avatar\\User\\" + protocol.FileName; if (sendFile(protocol, AvatarSaveFilePath)) { returnProtocol = new Network.TCP_FileProtocol(LYFZ.Network.EnumerateLibrary.InformationType.Message, "头像下载成功!"); } else { returnProtocol = new Network.TCP_FileProtocol(LYFZ.Network.EnumerateLibrary.InformationType.Message, "头像下载失败!"); } break; default: returnProtocol = new Network.TCP_FileProtocol(LYFZ.Network.EnumerateLibrary.InformationType.Message, "文件请求命令:" + Command + "无效!"); break; } return returnProtocol; } */ #endregion /* #region 服务器端接收文件方法 /// /// 获取连接到远程的流 -- 公共方法 /// /// /// /// private NetworkStream getStreamToClient(TCP_FileProtocol protocol, out TcpClient localClient) { // 获取远程客户端的位置 IPEndPoint endpoint = client.Client.RemoteEndPoint as IPEndPoint; IPAddress ip = endpoint.Address; // 使用新端口号,获得远程用于接收文件的端口 // endpoint = new IPEndPoint(ip, protocol.ClientPort); // 连接到远程客户端 try { localClient = new TcpClient(); localClient.Connect(endpoint); } catch { LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("客户端>>{0}文件传输通道连接失败...", client.Client.RemoteEndPoint)); localClient = null; return null; } // 获取发送文件的流 NetworkStream streamToClient = localClient.GetStream(); return streamToClient; } /// /// 接收文件 /// /// /// 文件要保存的完全路径名 private bool receiveFile(TCP_FileProtocol protocol,string fileFullName) { try { // 连接到远程客户端 TcpClient receiveLocalClient; // 获取发送文件的流 NetworkStream receiveStreamToClient = getStreamToClient(protocol, out receiveLocalClient); // 随机生成一个在当前目录下的文件名称 //string path = Environment.CurrentDirectory + "\\" + generateFileName(protocol.FileName); byte[] fileBuffer = new byte[BufferSize]; // 1024每次收1KB FileStream fs = new FileStream(fileFullName, FileMode.Create, FileAccess.Write); // 从缓存buffer中读入到文件流中 int bytesRead; int totalBytes = 0; do { Array.Clear(fileBuffer, 0, fileBuffer.Length); // 清空缓存,避免脏读 bytesRead = receiveStreamToClient.Read(fileBuffer, 0, BufferSize); fs.Write(fileBuffer, 0, bytesRead); totalBytes += bytesRead; // if (bytesRead > 0) // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("已接收数据:{0} Bytes ,数据来源客户端>>{1}", totalBytes, client.Client.RemoteEndPoint)); } while (bytesRead > 0); // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("共有{0} Bytes 接收的字节数,完成!,数据来源客户端>>{1}", totalBytes, client.Client.RemoteEndPoint)); receiveStreamToClient.Dispose(); fs.Dispose(); receiveLocalClient.Close(); if (totalBytes > 0) { return true; } else { return false; } } catch(Exception ex) { LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("接收文件错误:{0}",ex.Message)); return false; } } #endregion #region 服务器端向客户端发送文件处理方法 /// /// 服务器端向客户端发送文件 /// /// /// 要发送的文件 private bool sendFile(TCP_FileProtocol protocol, string fileFullName) { try { TcpClient localClient; NetworkStream sendStreamToClient = getStreamToClient(protocol, out localClient); // 获得文件的路径 string filePath = fileFullName; if (File.Exists(filePath)) { // 创建文件流 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] fileBuffer = new byte[BufferSize]; // 每次传1KB int bytesRead; int totalBytes = 0; // 创建获取文件发送状态的类 TCP_SendStatus status = new TCP_SendStatus(filePath); // 将文件流转写入网络流 try { do { // Thread.Sleep(1); // 为了更好的视觉效果,暂停1毫秒:-) Array.Clear(fileBuffer, 0, fileBuffer.Length); // 清空缓存,避免脏读 bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length); sendStreamToClient.Write(fileBuffer, 0, bytesRead); totalBytes += bytesRead; // 发送了的字节数 string statusMsg = status.GetStatus(totalBytes); // 打印发送状态 // if (bytesRead > 0) // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("{0} ,数据发往客户端>>{1}", statusMsg, client.Client.RemoteEndPoint)); } while (bytesRead > 0); // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("共有{0} Bytes 发送完成!,数据发往客户端>>{1}", totalBytes, client.Client.RemoteEndPoint)); } catch { totalBytes = 0; LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("错误:客户端连接已失去... ,数据发往客户端>>{0}", client.Client.RemoteEndPoint)); } sendStreamToClient.Dispose(); fs.Dispose(); localClient.Close(); if (totalBytes > 0) { return true; } else { return false; } } else { return false; } } catch { return false; } } #endregion }*/ }