123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604 |
- 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
- {
- /* /// <summary>
- /// 远程数据处理类 主动模式
- /// </summary>
- public class TCP_RemoteDataHandler
- {
- private TcpClient client;
- public TcpClient Client
- {
- get { return client; }
- set { client = value; }
- }
- /// <summary>
- /// 来至远程的网络数据流
- /// </summary>
- private NetworkStream streamToClient;
- /// <summary>
- /// 来至远程的网络数据流
- /// </summary>
- public NetworkStream StreamToClient
- {
- get { return streamToClient; }
- set { streamToClient = value; }
- }
- /// <summary>
- /// 缓冲字节大小
- /// </summary>
- private const int bufferSize = 8192;
- /// <summary>
- /// 缓冲字节大小
- /// </summary>
- public int BufferSize
- {
- get { return bufferSize; }
- }
- /// <summary>
- /// 缓冲字节数组
- /// </summary>
- private byte[] buffer;
- /// <summary>
- /// 缓冲字节数组
- /// </summary>
- public byte[] Buffer
- {
- get { return buffer; }
- set { buffer = value; }
- }
- /// <summary>
- /// 协议处理对象
- /// </summary>
- private TCP_ProtocolHandler handler;
- /// <summary>
- /// 协议处理对象
- /// </summary>
- public TCP_ProtocolHandler Handler
- {
- get { return handler; }
- set { handler = value; }
- }
- /// <summary>
- /// 初始化
- /// </summary>
- /// <param name="client"></param>
- public TCP_RemoteDataHandler(TcpClient client)
- {
- this.client = client;
- // 获得流
- streamToClient = client.GetStream();
- buffer = new byte[BufferSize];
- handler = new TCP_ProtocolHandler();
- }
- /// <summary>
- /// 读取信息
- /// </summary>
- /// <param name="stream"></param>
- /// <returns></returns>
- 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 服务器端创建客户端连接
- /// <summary>
- /// 创建客户端连接
- /// </summary>
- 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));
- }
- }
- /// <summary>
- /// 创建客户端连接
- /// </summary>
- 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));
- }
- }
-
- }
- /// <summary>
- /// 创建服务器到客户端的连接
- /// </summary>
- /// <param name="listener"></param>
- 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 客户端处理来至服务器的连接
- /// <summary>
- /// 客户端处理方法
- /// </summary>
- 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 客户端发送指令到服务端处理方法
- /* /// <summary>
- /// 发送指令到服务端并返回服务器的处理结果
- /// </summary>
- /// <param name="command">要发送到服务器的指令</param>
- /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
- /// <returns></returns>
- 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 服务器接收并处理客户端请求
- /* /// <summary>
- /// 服务器开始进行异步读取
- /// </summary>
- public void BeginRead()
- {
- AsyncCallback callBack = new AsyncCallback(OnReadComplete);
- streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null);
- }
- /// <summary>
- /// 再读取完成时进行回调
- /// </summary>
- /// <param name="ar"></param>
- 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();
- }
- }
- /// <summary>
- /// 当客户端连接断开时执行方法
- /// </summary>
- private void ClientDisconnected() {
- //根据实际需要实现相应功能
- LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("客户端连接断开时执行结果:{0}", "暂无处理!"));
- }
- /// <summary>
- /// 向当前网络流写入数据
- /// </summary>
- /// <param name="value"></param>
- public void StreamWrite(string value)
- {
- byte[] temp = Encoding.Unicode.GetBytes(value); // 获得缓存
- try
- {
- lock (StreamToClient)
- {
- StreamToClient.Write(temp, 0, temp.Length); // 将连接请求发往服务器
- }
- }
- catch {
-
- }
- }
- /// <summary>
- /// 服务器读取到端客户端数据后的处理程序protocol
- /// </summary>
- /// <param name="obj"></param>
- 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());
- }
- }
- /// <summary>
- /// 文件传输处理方法
- /// </summary>
- /// <param name="protocol"></param>
- /// <returns></returns>
- 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 服务器端接收文件方法
- /// <summary>
- /// 获取连接到远程的流 -- 公共方法
- /// </summary>
- /// <param name="protocol"></param>
- /// <param name="localClient"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 接收文件
- /// </summary>
- /// <param name="protocol"></param>
- /// <param name="fileFullName">文件要保存的完全路径名</param>
- 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 服务器端向客户端发送文件处理方法
- /// <summary>
- /// 服务器端向客户端发送文件
- /// </summary>
- /// <param name="protocol"></param>
- /// <param name="fileFullName">要发送的文件</param>
- 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
-
- }*/
- }
|