54SA.COM|专注于系统运维管理,为中国SA提供动力!
Getting online shouldn't be tough. $7.99 .COMs
系统管理员之家Banner
当前位置: 主页 > 编程开发 > C#开发 >

C# TCP发送消息和传输文件(五)

时间:2011-07-05 16:58来源:未知 编辑:admin

调用的代码

server:

 

Code
public void DoWork(object state)
        {
            TcpListenerHelper tlistener = (TcpListenerHelper)state;
            tlistener.Listen();
//监听

            
while (tlistener.WaitForConnect())//等待知道监听到了连接
            {
                
try
                {
                    
string firstMessage = "";
                    
while (!string.IsNullOrEmpty((firstMessage = tlistener.ReadMessage())))
                    {
                        
if (firstMessage.ToLower() == "filebak".ToLower())
                        {
                            tlistener.SendMessage(
"filebakok");
                            
#region 文件备份
                            
string filepath = Path.Combine(Environment.CurrentDirectory, "FileBak\\" + tlistener.ReadMessage()).ToString();
                            tlistener.ReceiveFile(filepath);
                            
if (tlistener.CalcFileHash(filepath) == tlistener.ReadMessage())
                            {
                                tlistener.SendMessage(
"ok");
                            }
                            
else
                            {
                                tlistener.SendMessage(
"wrong");
                            }
                            
#endregion
                        }
                        
else if (firstMessage.ToLower() == "DBBak".ToLower())
                        {
                            
#region 数据库备份
                            tlistener.SendMessage(
"dbbakok");
                            
string filename = tlistener.ReadMessage();
                            
string filepath = Path.Combine(System.Environment.CurrentDirectory, "DBBak") +"\\"+ filename;
                            
//接收文件
                            tlistener.ReceiveFile(filepath);
                            
//验证hash
                            string hash = tlistener.ReadMessage();
                            
if (hash == tlistener.CalcFileHash(filepath))
                                tlistener.SendMessage(
"ok");
                            
else
                                tlistener.SendMessage(
"wrong");

                            
#endregion
                        }
                    }
                }
                
catch
                {
                }

                tlistener.Listen();
//监听下一个连接
            }
        }

C# TCP发送消息和传输文件(一)开发背景
C# TCP发送消息和传输文件(二)TcpCommon
C# TCP发送消息和传输文件(三)TcpClientHelper
C# TCP发送消息和传输文件(四)TcpListenerHelper
C# TCP发送消息和传输文件(五)server端
C# TCP发送消息和传输文件(六)client端

[责任编辑:admin]


------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
用户名:
最新评论 进入详细评论页>>