基于Socket通信的BS结构文件服务器客户端的简易程序(3)

http://blog.csdn.net/weixingstudio/article/details/7042290

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Collections;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Xml;
using System.Collections.Specialized;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Server
{
    public partial class Server_Form : Form
    {
        // 服务器地址默认为10.108.13.27, 端口为8888
        private int PORT = 8888;
        private string ip_server = "10.108.13.27";

        private IPAddress ipAddress_Server = null;
        // 维护一个所有用户客户端的哈希表
        private Hashtable client_hashtable = null;
        // 监听端口的类
        private TcpListener listener_server = null;
        // 监听端口用的线程
        private Thread thread_port_listening = null;
        private Thread client_Thread = null;

        // 用于目录管理的基本路径
        private string config_path=Environment.CurrentDirectory + "\\config";
        private string user_info=Environment.CurrentDirectory+ "\\config" + "\\user_config";

        // 保存用户名和密码的文件
        private string user_account_path = Environment.CurrentDirectory + "\\config" + "\\user_config" + "\\user_account.txt";

        Add_user add_user_form = null;

        //private long maxFileBuffer = 1024 * 1024;//最大可以传送大小为1M 的文件,暂时这样处理,减少缓冲区的工作量
        private int fileBuffer_eachTime_sended = 8 * 1024;// 每次最多传送8K , 先这样测测

        delegate void setOnlineUserInfoDelegate(string s);
        delegate void showInfoDelegate(string s);
        delegate void clearOnlineUserDelegate();

        // 服务器和客户机协约的通信协议
        // "00" 同意连接
        // "01" 拒绝连接
        // "10" 用户请求离线
        // "11" 通知用户刷新在线用户列表
        // "12" 请求在线用户列表
        // "22" 通知用户有其他的用户上线了
        // "23" 通知所有用户有人离线
        // "33" 用户请求上传文件
        // "34" 文件上传成功
        // "44" 用户请求文件列表
        // "45" 给用户返回文件列表
        // "55" 用户请求下载文件
        // "56" 给用户发送文件
        // "66" 用户请求删除文件
        // "67" 删除文件成功

        public Server_Form()
        {
            InitializeComponent();
            InitServerForm();
            // 当前窗口关闭是进行的操作
            this.FormClosed += new FormClosedEventHandler(Server_Form_FormClosed);

            // 关闭线程安全检查,否则会出很多线程错误
            //Form.CheckForIllegalCrossThreadCalls = false;
            // 初始化相关配置
            string currentPath = Environment.CurrentDirectory;
            string fileFolder = currentPath + "\\" + "files";
            string configFolder = currentPath + "\\" + "config";
            bool test = Directory.Exists(fileFolder);
            if (test)
            {
                // 存在目录则不进行操作
            }
            else
            {
                // 创建各个用户存放文件的目录
                Directory.CreateDirectory(fileFolder);
            }
            if (!Directory.Exists(configFolder))
            {
                string user_config_folder = configFolder + "\\" + "user_config";
                Directory.CreateDirectory(configFolder);
                Directory.CreateDirectory(user_config_folder);
            }

            string userXMLFile = configFolder + "\\user_config" + "\\user.xml";
            if (!File.Exists(userXMLFile))
            {
                try
                {
                    // 创建用户账户文件
                    XmlDocument doc = new XmlDocument();
                    XmlDeclaration xmld = doc.CreateXmlDeclaration("1.0", "GB2312", null);
                    XmlElement root = doc.CreateElement("user");
                    doc.AppendChild(xmld);
                    doc.AppendChild(root);
                    doc.Save(configFolder + "\\user_config\\" + "user.xml");
                }
                catch (FileLoadException)
                { }
                catch (FileNotFoundException)
                { }
                finally
                {
                    //
                }
            }
        }

        /// <summary>
        /// 当窗体关闭时,进行处理操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Server_Form_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 关闭窗口时,判断端口监听线程是否已经关闭,如果端口监听线程没有关闭,则关闭端口监听线程
            if (thread_port_listening!=null)
            {
                // 关闭监听服务
                //listener_server.Stop();
                // 关闭线程
                thread_port_listening.Abort();
            }
        }

        /// <summary>
        ///  初始化窗口的一些参数
        /// </summary>
        private void InitServerForm()
        {
            this.textBox_ip.Text = "10.108.13.27";
            this.textBox_port.Text = "8888";
        }

        /// <summary>
        /// 开启监听服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 校验 参数
            bool isTheParamsRight=VerifyInputParams();
            // 如果参数不正确,则提示错误信息
            if (!isTheParamsRight)
            {
                //MessageBox.Show("请确认输入正确的参数信息","info",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            // 监听线程没有创建实例,服务还没有开始
            if (thread_port_listening == null)
            {
                // 显示提示消息
                this.richTextBox1.AppendText("start service:" + ip_server + ":" + PORT + '\n');
                // 初始化IPAddress
                ipAddress_Server = IPAddress.Parse(ip_server);
                // 初始化客户端Hashtable
                client_hashtable = new Hashtable();
                // 初始化端口监听类
                listener_server = new TcpListener(ipAddress_Server, PORT);

                thread_port_listening = new Thread(new ThreadStart(ListenPort));
                this.richTextBox1.AppendText("new listening thread started" + '\n');
                thread_port_listening.Start();
            }
            else
            {
                this.richTextBox1.AppendText("service already started! pls do not start any more!!!"+'\n');
            }
        }

        /// <summary>
        /// 开始监听端口,在一个新的线程中
        /// </summary>
        private void ListenPort()
        {
            // 开始监听服务器端口,接受客户端的连接
            listener_server.Start();
            string info = "service start successfully." + '\n';
            // 线程安全地显示相关信息
            showInfo_richbox1(info);

            // 显示在线用户人数
            show_Online_User();

            try
            {
                // 开始不停地监听端口,并为每一个连接的客户端创建一个新的线程
                while (true)
                {
                    // 定义一个接受信息缓冲区
                    // 缓冲区大小为8K
                    byte[] info_buffer = new byte[8096];

                    // 建立一个和客户端进行会话的Socket连接
                    Socket newClinet = listener_server.AcceptSocket();
                    // 获取用户提交的用户名
                    newClinet.Receive(info_buffer);
                    newClinet.Send(new byte[] { 1, 1 });

                    string user_Name = Encoding.Unicode.GetString(info_buffer).TrimEnd('\0');
                    // 获得用户提交的密码  
                    byte[] passbuffer = new byte[100];
                    newClinet.Receive(passbuffer);
                    string user_Password = Encoding.Unicode.GetString(passbuffer).TrimEnd('\0');

                    // 判断用户是否有权限连接服务器
                    bool isUserAllowedConnect = VerifyUser(user_Name, user_Password);
                    if (isUserAllowedConnect)
                    {
                        // 用户是合法的连接用户
                        // 发送允许连接代码
                        newClinet.Send(Encoding.Unicode.GetBytes("success"));
                        // 为用户建立一个专用的线程进行通信
                        // 将登录的用户记录在hashtable中
                        client_hashtable.Add(user_Name, newClinet);
                        client_Thread = new Thread(new ParameterizedThreadStart(tcpClient_Thread));
                        // 开始和用户通信的专用线程
                        try
                        {
                            client_Thread.Start(user_Name);
                        }
                        catch (ThreadStartException)
                        {
                            //
                        }
                        // 通知所有的用户XX上线了
                        // 先给每个用户发送有人上线指令
                        foreach (DictionaryEntry de in client_hashtable)
                        {
                            string name = de.Key.ToString();
                            Socket s = de.Value as Socket;
                            string temp = "用户:" + user_Name + "上线了!";
                            if (!name.Equals(user_Name))
                            {
                                s.Send(new byte[] { 2, 2 }); // 发送有人上线指令
                                s.Send(Encoding.Unicode.GetBytes(temp));
                            }
                        }
                        // 在信息里面显示登录信息
                        string login_info = '\n' + user_Name + "登录了" + '\n';
                        showInfo_richbox1(login_info);
                        // 刷新在线用户列表
                        show_Online_User();
                    }
                    else
                    {
                        // 不合法的用户, 发送拒绝连接代码
                        newClinet.Send(Encoding.Unicode.GetBytes("failed"));
                        continue;//结束本次监听循环
                    }
                }
            }
            catch (ThreadAbortException)
            {
                //
            }
            finally
            {
                //
            }
        }

        /// <summary>
        /// 负责和登录用户进行通信的专用线程
        /// </summary>
        /// <param name="userName">传递用户名</param>
        private void tcpClient_Thread(object userName)
        {
            string name = userName as string;
            // 获得和用户通信的Socket
            try
            {
                Socket clientSocket = client_hashtable[userName] as Socket;
                if (clientSocket != null)
                {
                    // 不停的接收用户请求并做出相应响应,接收和响应是对应的一对一的
                    while (clientSocket.Connected)
                    {
                        byte[] commandBuffer = new byte[4];
                        // 接收用户发过来的命令请求
                        if (!clientSocket.Connected)
                        {
                            // 
                            break;
                        }
                        clientSocket.Receive(commandBuffer);
                        // 解码命令 
                        string cmd = DecodingBytes(commandBuffer);

                        switch (cmd)
                        {
                            // 用户请求离线
                            case "10":
                                {
                                    // 关闭用户的Socket连接,然后清理用户的hashtable
                                    client_hashtable.Remove(userName);
                                    string info = "\n用户" + name + "离线了\n";
                                    // 在信息里面显示登录信息
                                    showInfo_richbox1(info);
                                    // 通知所有的用户XX离线了, 给每个Socket连接发送消息,需要使用每个Socket连接各自的Socket
                                    foreach (DictionaryEntry de in client_hashtable)
                                    {
                                        Socket s = de.Value as Socket;
                                        if (!de.Key.Equals(userName))
                                        {
                                            // 先给各个用户发送有人离线指令
                                            s.Send(new byte[] { 2, 3 });
                                            s.Send(Encoding.Unicode.GetBytes(info));
                                        }
                                    }
                                    // 刷新在线用户列表
                                    show_Online_User();
                                    // 终止当前线程
                                    Thread.CurrentThread.Abort();
                                    break;
                                }
                            // 用户请求在线用户列表
                            case "12":
                                {
                                    byte[] onLineUserBuffer = SerializeOnlineList();
                                    // 先给客户机发送响应信号,通知客户机刷新用户列表
                                    clientSocket.Send(new byte[] { 1, 1 });
                                    // 发送在线用户列表
                                    clientSocket.Send(onLineUserBuffer);
                                    break;
                                }
                            // 用户请求上传文件
                            case "33":
                                {
                                    try
                                    {
                                        // 
                                        // 存放文件到用户的文件夹目录
                                        byte[] fileBuffer = new byte[fileBuffer_eachTime_sended];
                                        byte[] fileNameBuffer = new byte[256];
                                        // 接收文件名 
                                        clientSocket.Receive(fileNameBuffer);
                                        string fileName = Encoding.Unicode.GetString(fileNameBuffer).TrimEnd('\0');
                                         接收要传送的次数
                                        //byte[] times_byte = new byte[8];
                                        //clientSocket.Receive(times_byte);
                                        //string temp = Encoding.Unicode.GetString(times_byte).TrimEnd('\0');
                                        //int number_of_receive = int.Parse(temp);
                                        // 接收总的文件大小
                                        byte[] fileSize_byte = new byte[16];
                                        clientSocket.Receive(fileSize_byte);
                                        string fileSize_string = Encoding.Unicode.GetString(fileSize_byte).TrimEnd('\0');
                                        long sumFileSize = Convert.ToInt32(fileSize_string, 10);
                                        // 由文件的大小计算传送的次数
                                        long number_of_receive = sumFileSize / fileBuffer_eachTime_sended + 1;
                                        // 
                                        string filePath = Environment.CurrentDirectory + "\\files";
                                        string userPath = filePath + "\\" + name + "\\" + fileName; // 文件的完全存储路径

                                        FileStream file = File.Open(userPath, FileMode.Create, FileAccess.ReadWrite);
                                        BinaryWriter bw = new BinaryWriter(file);

                                        // 向文件中写数据
                                        if (number_of_receive == 1)
                                        {
                                            // 只需要传送一次
                                            int FileSize = clientSocket.Receive(fileBuffer);
                                            bw.Write(fileBuffer, 0, FileSize);
                                            bw.Flush();
                                        }
                                        else if (number_of_receive > 1)
                                        {
                                            // 需要多次接收文件
                                            for (int i = 1; i < number_of_receive; i++)
                                            {
                                                clientSocket.Receive(fileBuffer);
                                                bw.Write(fileBuffer, 0, fileBuffer_eachTime_sended);
                                                bw.Flush();
                                            }
                                            // 通过总的文件大小,计算最后传送的个数 
                                            int remainBytes = (int)(sumFileSize % fileBuffer_eachTime_sended);
                                            byte[] newBuffer = new byte[remainBytes];
                                            clientSocket.Receive(newBuffer);
                                            bw.Write(newBuffer, 0, remainBytes);
                                            bw.Flush();
                                        }
                                        bw.Close();
                                        file.Close();

                                        // 判断文件是否上传成功
                                        bool success = File.Exists(userPath);
                                        if (success)
                                        {
                                            // 文件上传成功
                                            // 将文件的相关信息存储到配置文件,fileName,FileSize,time
                                            FileStream fs = File.Open(userPath, FileMode.Open);
                                            long fz = fs.Length;
                                            fs.Close();
                                            DateTime dt = DateTime.Now;
                                            XmlDocument doc = new XmlDocument();
                                            doc.Load(filePath + "\\" + name + "\\" + "config.xml");
                                            XmlElement root = doc.DocumentElement;
                                            XmlElement child = doc.CreateElement("file");
                                            child.SetAttribute("FileName", fileName);
                                            child.SetAttribute("FileSize", fz.ToString() + "B");
                                            child.SetAttribute("Time", dt.ToString());
                                            root.InsertAfter(child, root.LastChild);
                                            doc.Save(filePath + "\\" + name + "\\" + "config.xml");
                                            // 文件上传成功,给用回返回确认信息
                                            //clientSocket.Send(Encoding.Unicode.GetBytes("upload_completed"));
                                            clientSocket.Send(new byte[] { 3, 4 });
                                        }
                                    }
                                    catch (FileLoadException)
                                    {
                                        //
                                    }
                                    catch (FileNotFoundException)
                                    {
                                        //
                                    }
                                    break;
                                }
                            // 用户请求服务器文件列表
                            case "44":
                                {
                                    string configPath = Environment.CurrentDirectory + "\\files" + "\\" + name + "\\" + "config.xml";
                                    XmlDocument doc = new XmlDocument();
                                    doc.Load(configPath);
                                    XmlElement root = doc.DocumentElement;
                                    StringCollection cs = new StringCollection();
                                    foreach (XmlElement child in root.ChildNodes)
                                    {
                                        string FileName = child.GetAttribute("FileName");
                                        string FileSize = child.GetAttribute("FileSize");
                                        string datetime = child.GetAttribute("Time");
                                        cs.Add(FileName);
                                        cs.Add(FileSize);
                                        cs.Add(datetime);
                                    }
                                    // 将文件列表序列化返回给用户
                                    IFormatter format = new BinaryFormatter();
                                    MemoryStream ms = new MemoryStream();
                                    format.Serialize(ms, cs);
                                    byte[] result = ms.ToArray();
                                    ms.Close();
                                    // 发送列表之前先发送传送文件列表命令
                                    clientSocket.Send(new byte[] { 4, 5 });
                                    // 发送文件列表
                                    clientSocket.Send(result);
                                    break;
                                }
                            // 用户下载文件请求
                            case "55":
                                {
                                    byte[] fileNameBuffer = new byte[128];
                                    clientSocket.Receive(fileNameBuffer);
                                    // 获得要下载的文件名
                                    string fileName = Encoding.Unicode.GetString(fileNameBuffer).TrimEnd('\0');
                                    string filePath = Environment.CurrentDirectory + "\\files" + "\\" + name + "\\" + fileName;
                                    try
                                    {
                                        FileStream fs = File.Open(filePath, FileMode.Open);
                                        long fileSize = fs.Length;
                                        BinaryReader br = new BinaryReader(fs);
                                        // 发送给用户传送文件的命令
                                        clientSocket.Send(new byte[] { 5, 6 });
                                        // 传送文件, 分开传送,如果文件大于8k,则分为8k为一个传送单位
                                        // 用来存储即将发送的数据
                                        byte[] bytes_tobesend = new byte[fileBuffer_eachTime_sended];  // 最大8k
                                        // 计算需要发送的次数
                                        int times_tobesended = (int)(fileSize / fileBuffer_eachTime_sended) + 1;
                                        //string times_string = times_tobesended.ToString();
                                         传送给客户端需要发送的次数
                                        //byte[] times_byte = Encoding.Unicode.GetBytes(times_string);
                                        //clientSocket.Send(times_byte);
                                        // 
                                        //  传送总的文件大小
                                        clientSocket.Send(Encoding.Unicode.GetBytes(fileSize.ToString().TrimEnd('\0')));
                                        // 开始传送文件
                                        if (times_tobesended == 1)
                                        {
                                            // 只需要传送一次
                                            byte[] bytes_Only1time = new byte[fileSize];
                                            br.Read(bytes_Only1time, 0, (int)fileSize);
                                            clientSocket.Send(bytes_Only1time);
                                        }
                                        else if (times_tobesended > 1)
                                        {
                                            // 需要传送的次数>1, 需要分多次传送
                                            for (int i = 1; i < times_tobesended; i++)
                                            {
                                                bytes_tobesend = br.ReadBytes(fileBuffer_eachTime_sended);
                                                //br.Read(bytes_tobesend, 0, fileBuffer_eachTime_sended);
                                                if (clientSocket.Connected)
                                                {
                                                    clientSocket.Send(bytes_tobesend);
                                                }
                                                else
                                                {
                                                    // 用户连接丢失,进行清理工作
                                                    client_hashtable.Remove(name); // 在hashtable中移除用户
                                                    string s = "\n 用户:" + name + "发生异常,失去连接\n";
                                                    // 在提示框中提示消息
                                                    showInfo_richbox1(s);
                                                    // 终结当前线程
                                                    Thread.CurrentThread.Abort();
                                                }
                                                //Thread.Sleep(10);
                                            }
                                            int remainedBytes = (int)(fileSize % fileBuffer_eachTime_sended); // 计算剩余的字节数
                                            byte[] to_be_send_remain = new byte[remainedBytes];
                                            to_be_send_remain = br.ReadBytes(remainedBytes);
                                            //br.Read(bytes_tobesend, 0, remainedBytes);
                                            clientSocket.Send(to_be_send_remain);
                                        }
                                        br.Close();
                                        fs.Close();
                                    }
                                    catch (FileLoadException)
                                    {
                                        //
                                    }
                                    finally
                                    {
                                        //
                                    }
                                    break;
                                }
                            // 用户请求删除文件
                            case "66":
                                {
                                    // 获取文件名
                                    byte[] fileNameBuffer = new byte[128];
                                    clientSocket.Receive(fileNameBuffer);
                                    string fileName = Encoding.Unicode.GetString(fileNameBuffer).TrimEnd('\0');
                                    // 获取要删除文件的路径
                                    string filePath = Environment.CurrentDirectory + "\\files" + "\\" + name + "\\" + fileName;
                                    File.Delete(filePath);
                                    // 清理记录文档
                                    string configPath = Environment.CurrentDirectory + "\\files" + "\\" + name + "\\" + "config.xml";
                                    XmlDocument doc = new XmlDocument();
                                    doc.Load(configPath);
                                    XmlElement root = doc.DocumentElement;
                                    foreach (XmlElement child in root.ChildNodes)
                                    {
                                        string filename = child.GetAttribute("FileName");
                                        if (filename.Equals(fileName))
                                        {
                                            root.RemoveChild(child);
                                            break;
                                        }
                                        continue;
                                    }
                                    doc.Save(configPath);
                                    // 发送删除文件成功代码
                                    clientSocket.Send(new byte[] { 6, 7 });
                                    break;
                                }
                            default:
                                {
                                    break;
                                }
                        }
                    } // end while
                    if (!clientSocket.Connected)
                    {
                        // 用户连接丢失,进行清理工作
                        client_hashtable.Remove(name); // 在hashtable中移除用户
                        string s = "\n 用户:" + name + "发生异常,失去连接\n";
                        // 在提示框中提示消息
                        showInfo_richbox1(s);
                        clientSocket = null;
                        // 终结当前线程
                        Thread.CurrentThread.Abort();
                    }
                }
                else
                {
                    // todo?
                }
            }
            catch (SocketException)
            {
                //
                // 和用户的连接异常后,清理工作
                // 用户连接丢失,进行清理工作
                client_hashtable.Remove(name); // 在hashtable中移除用户
                string s = "\n 用户:" + name + "发生异常,失去连接\n";
                // 在提示框中提示消息
                showInfo_richbox1(s);
                // 显示在线用户人数
                show_Online_User();
                // 终结当前线程
                Thread.CurrentThread.Abort();
            }
            finally
            {
                // 
            }
        }

        /// <summary>
        /// 序列化在线列表,向客户端返回序列化后的字节数组
        /// </summary>
        /// <returns>序列化后的字节数组</returns>
        private byte[] SerializeOnlineList()
        {
            StringCollection onlineList = new StringCollection();
            foreach (object o in client_hashtable.Keys)
            {
                onlineList.Add(o as string);//转换语句
            }
            IFormatter format = new BinaryFormatter();//以二进制格式将对象或整个连接对象图形序列化和反序列化。
            MemoryStream stream = new MemoryStream();
            format.Serialize(stream, onlineList);//保持到内存流
            byte[] ret = stream.ToArray();
            stream.Close();
            return ret;
        }

        /// <summary>
        /// 将命令解码
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private string DecodingBytes(byte[] s)
        {
            return string.Concat(s[0].ToString(), s[1].ToString());
        }

        /// <summary>
        /// 线程安全的在richTextBox中显示信息
        /// </summary>
        /// <param name="info"></param>
        private void showInfo_richbox1(string info)
        {
            // 通过代理,线程安全的在控件中显示信息
            if (this.richTextBox1.InvokeRequired)
            {
                // 通过代理,保证线程安全性
                showInfoDelegate call = delegate(string s) { this.richTextBox1.AppendText(info); };
                this.richTextBox1.Invoke(call,info);
            }
            else
            {
                this.richTextBox1.AppendText(info);
            }
            //
            //if (this.onlineUserInfo.InvokeRequired)
            //{
            //    setOnlineUserInfoDelegate call = delegate(string s)
            //    {
            //        this.onlineUserInfo.Clear();
            //        this.onlineUserInfo.AppendText(s);
            //    };
            //    this.onlineUserInfo.Invoke(call, info);
            //}
            //else
            //{
            //    this.onlineUserInfo.Clear();
            //    this.onlineUserInfo.AppendText(info);
            //}
        }

        /// <summary>
        /// 判断用户是否有权限访问服务器
        /// </summary>
        /// <param name="user_Name"></param>
        /// <param name="user_Password"></param>
        /// <returns></returns>
        private bool VerifyUser(string user_Name, string user_Password)
        {
            try
            {
                // 在用户管理文件中查询用户名,密码是否正确
                XmlDocument doc = new XmlDocument();
                doc.Load(".//config//user_config//user.xml");
                XmlElement root = doc.DocumentElement;
                foreach (XmlElement accout in root.ChildNodes)
                {
                    string name = accout.GetAttribute("name");
                    string password = accout.GetAttribute("password");
                    if (name.Equals(user_Name) && password.Equals(user_Password))
                    {
                        return true;
                    }
                }
            }
            catch (FileLoadException)
            {
                //
            }
            finally
            {
                //
            }
            return false;
        }

        /// <summary>
        /// 关闭服务,结束端口监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void stop_service(object sender, EventArgs e)
        {
            if (listener_server != null)
            {
                // 如果不为空,则停止监听
                this.richTextBox1.AppendText("\n服务结束!" + '\n');
                listener_server.Stop();
                listener_server = null;

                // 结束监听线程 并且设为null
                thread_port_listening.Abort();
                thread_port_listening = null;

                MessageBox.Show("服务终止","info");
            }

            if (client_hashtable != null)
            {
                // 停止监听以后,结束所有的在hashtable中的客户端
                if (client_hashtable.Count != 0)
                {
                    // 关闭所有的会话连接
                    foreach (Socket sesson in client_hashtable.Values)
                    {
                        sesson.Shutdown(SocketShutdown.Both);
                    }
                    // 清空hashtable
                    client_hashtable.Clear();
                    client_hashtable = null;

                    this.richTextBox1.AppendText("client all removed!!!" + '\n');
                }
            }
        }

        /// <summary>
        /// 显示在线用户的方法
        /// </summary>
        private void show_Online_User()
        {
            if (client_hashtable != null)
            {
                if (client_hashtable.Count != 0)
                {
                    //this.onlineUserInfo.Clear();
                    clearOnlineUser();
                    //this.onlineUserInfo.AppendText("当前在线的用户有:" + '\n');
                    showOnlineUser("当前在线的用户有:");
                    foreach (string name in client_hashtable.Keys)
                    {
                        string temp = name;
                        //this.onlineUserInfo.AppendText(name + '\n');
                        showOnlineUser(name);
                    }
                }
                else
                {
                    // 不是线程安全的,容易出现错误
                    //this.onlineUserInfo.Clear();
                    //this.onlineUserInfo.AppendText("当前没有用户在线");
                    setOnLineUserInfo();
                }
            }
        }

        private void showOnlineUser(string info)
        {
            if (this.onlineUserInfo.InvokeRequired)
            {
                showInfoDelegate call = delegate(string s) { this.onlineUserInfo.AppendText(s + '\n'); };
                this.onlineUserInfo.Invoke(call, info);
            }
            else
            {
                this.onlineUserInfo.AppendText(info + '\n');
            }
        }

        /// <summary>
        /// 线程安全的清除在线用户信息
        /// </summary>
        private void clearOnlineUser()
        {
            if (this.onlineUserInfo.InvokeRequired)
            {
                clearOnlineUserDelegate call = delegate() { this.onlineUserInfo.Clear(); };
                this.onlineUserInfo.Invoke(call);
            }
            else
            {
                this.onlineUserInfo.Clear();
            }
        }

        /// <summary>
        /// 线程安全的给控件添加信息
        /// </summary>
        private void setOnLineUserInfo()
        {
            string info = "当前没有用户在线";
            if (this.onlineUserInfo.InvokeRequired)
            { 
                setOnlineUserInfoDelegate call = delegate(string s) {
                    this.onlineUserInfo.Clear();
                    this.onlineUserInfo.AppendText(s); };
                this.onlineUserInfo.Invoke(call,info);
            }
            else
            {
                this.onlineUserInfo.Clear();
                this.onlineUserInfo.AppendText(info);
            }
        }

        /// <summary>
        /// 校验用户输入的参数是否正确
        /// </summary>
        /// <returns></returns>
        private bool VerifyInputParams()
        {
            if (textBox_ip.Text == "")
            {
                MessageBox.Show("请输入正确的IP","info",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return false;
            }
            this.ip_server = textBox_ip.Text;
            if (textBox_port.Text == "" || (int.Parse(textBox_port.Text)) < 1023 || (int.Parse(textBox_port.Text)) > 65535)
            {
                MessageBox.Show("请输入正确的port", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            this.PORT = int.Parse(textBox_port.Text);
            return true;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_add_user_Click(object sender, EventArgs e)
        {
            // 给记录文件中添加相应的用户
            add_user_form = new Add_user();
            add_user_form.Owner = this;
            add_user_form.Show();
            // 可见性改变的的时间发生以后,创建新的用户
            add_user_form.VisibleChanged += new EventHandler(add_user_form_VisibleChanged);      
        }

        /// <summary>
        /// 添加用户,xml文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void add_user_form_VisibleChanged(object sender, EventArgs e)
        {
            string name = null;
            string password = null;
            // 获取创建用户的用户名和密码
            name = add_user_form.name;
            password = add_user_form.password;

            // 获取值完全正确
            //MessageBox.Show(name+":"+password,"info");
            // 添加用户,使用xml文件配置用户信息
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(".//config//user_config//user.xml");
                XmlNode root = doc.DocumentElement;

                XmlElement newUser = doc.CreateElement("accout");
                newUser.SetAttribute("name", name);
                newUser.SetAttribute("password", password);

                root.InsertAfter(newUser, root.LastChild);
                doc.Save(".//config//user_config//user.xml");
                this.richTextBox1.AppendText("添加用户成功" + '\n');
                richTextBox1.AppendText("用户名:" + name);
                richTextBox1.AppendText(" 密码:" + password + '\n');
            }
            catch (FileLoadException)
            {
                //
            }
            finally
            {
                //
            }

            // 创建用户以后,给用户创建相应的文件夹,存放上传的文件
            createUserFolder();
            //fs.Flush();
            //fs.Close();
        }

        /// <summary>
        /// 给用户创建文件夹
        /// </summary>
        private void createUserFolder()
        {
            string name = add_user_form.name;
            // 创建和用户名一致的文件夹
            string filePath = Environment.CurrentDirectory + "\\files";
            string userPath = filePath + "\\" + name;
            try
            {
                Directory.CreateDirectory(userPath);

                // 创建文件夹以后在这个文件夹内创建用户的文件管理配置文件
                XmlDocument doc = new XmlDocument();
                XmlDeclaration xmld = doc.CreateXmlDeclaration("1.0", "GB2312", null);
                XmlElement root = doc.CreateElement("user");
                root.SetAttribute("name", name);
                doc.AppendChild(xmld);
                doc.AppendChild(root);
                doc.Save(userPath + "\\" + "config.xml");
            }
            catch(FileLoadException)
            {
                //
            }
        }

        private void Server_Form_Load(object sender, EventArgs e)
        {
            // todo
        }
    }
}


 

 

本程序源码的下载连接: http://download.csdn.net/detail/weixingstudio/3882186

欢迎大家有好的建议都告诉我。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值