利用TCP协议通过Socket编写的网络聊天工具2-通用类设计

在上一节中,还有即将给出的服务器代码,都使用了共同的工具类,包括一个Command类,用来负责表示通讯中的命令控制,一个ServerConfig类,用来表示服务器的配置,这个在客户端中也要使用,还有一个验证用户信息的类,在客户端使用。因为这三个类的通用新比较高,所以单独用一个dll工程来开发的这三个类,这样在客户端工程和服务器端工程中直接可以添加这个新的工程的DLL的引用。

 

整个项目源码下载地址:http://download.csdn.net/detail/weixingstudio/4301232

 

Command类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace UtilityClass
{
    /// <summary>
    /// 通讯系统用的命令
    /// </summary>
    public class Command
    {
        public const string Connect = "00";                    // 连接
        public const string ConnectConfirm = "01";             // 连接确认
        public const string DisConnect = "02";                 // 请求离开
        public const string RequestOnlineUser = "03";          // 请求在线用户列表
        public const string VibrateAll = "04";                 // 请求对所有人震动
        public const string VibrateOne = "05";                 // 请求对某人震动
        public const string BroadcastAll = "06";               // 对所有人广播消息
        public const string SendMessage2One = "07";            // 对指定人传送消息
        public const string RedundantUserName = "10";          // 重复的用户名
        public const string SomeoneConnected = "11";           // 通知有人上线
        public const string SomeoneLeaveUnexpected = "12";     // 某人异常离开
        public const string SomeoneLeave = "13";               // 有人离开
        public const string ServerShutdown = "14";             // 服务器关闭
        public const string ExceedMaxAllowedNumber = "15";     // 超出最大的允许连接数
        public const string SendOnlinUserList = "16";          // 发送用户列表

        /// <summary>
        /// 编码命令,返回命令的字节流
        /// </summary>
        /// <param name="cmd">需要编码的命令</param>
        /// <returns>返回字节流</returns>
        public static byte[] EncodeCommand(string cmd)
        {
            byte[] command_byte = Encoding.Unicode.GetBytes(cmd);
            return command_byte;
        }

        /// <summary>
        /// 解码系统命令,返回字符串
        /// </summary>
        /// <param name="cmd">待解码的密令</param>
        /// <returns>返回字符串</returns>
        public static string DecodeCommand(byte[] cmd)
        {
            string cmd_string = Encoding.Unicode.GetString(cmd).TrimEnd('\0');
            return cmd_string;
        }

        /// <summary>
        /// 序列化在线用户列表
        /// </summary>
        /// <param name="onlineuser">序列化数组</param>
        /// <returns>返回结果</returns>
        public static byte[] SerializeOnlineUser(string[] onlineuser)
        {
            StringCollection onlineuserCollection = new StringCollection();
            foreach (string user in onlineuser)
            {
                onlineuserCollection.Add(user);
            }
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, onlineuserCollection);
            byte[] result = stream.ToArray();
            stream.Close();
            return result;
        }

        /// <summary>
        /// 反序列化在线用户列表
        /// </summary>
        /// <param name="userbyte">输入的字节流</param>
        /// <returns>返回字符串集合</returns>
        public static StringCollection DeserializeOnlineUser(byte[] userbyte)
        {
            IFormatter format = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            stream.Write(userbyte, 0, userbyte.Length);
            stream.Position = 0;
            StringCollection onlineList = (StringCollection)format.Deserialize(stream);
            return onlineList;
        }

        /// <summary>
        /// 检查要传送的消息是否正确
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static bool VerifyMessage(string message)
        {
            if (!message.Equals(""))
            {
                // 检查是否都是空格
                char[] temp = message.ToArray();
                bool flag = false;
                foreach (char c in temp)
                {
                    if (c!=' '&& c!='\n' && c!=13)
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag==true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
                
            }
            else
            {
                return false;
            }
        }
    }
}


ServerConfig类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace UtilityClass
{
    public class ServerConfig
    {
        // server ip
        private string serverIP = "10.108.13.27";
        // server port
        private int serverPort = 8888;
        // max buffer for receive data from client, 56K
        private int maxBuffer = 56 * 1024;
        // IPAddress
        private IPAddress ipAddress;
        // max allowed online user
        private int maxAllowedOnlineUser = 100;


        public ServerConfig()
        {
            // 
        }

        public ServerConfig(string ip, int port)
        {
            this.serverIP = ip;
            this.serverPort = port;
        }

        public ServerConfig(string ip)
        {
            this.serverIP = ip;
            this.serverPort = 8888;
        }

        public ServerConfig(int port)
        {
            this.serverIP = "127.0.0.1";
            this.serverPort = port;
        }

        /// <summary>
        /// 服务器IP地址
        /// </summary>
        public string ServerIP
        {
            get { return serverIP; }
            set { serverIP = value; }
        }

        /// <summary>
        /// 服务器监听端口
        /// </summary>
        public int ServerPort
        {
            get { return serverPort; }
            set { serverPort = value; }
        }

        /// <summary>
        /// 最大数据缓冲区
        /// </summary>
        public int MaxBuffer
        {
            get { return maxBuffer; }
            set { maxBuffer = value; }
        }

        /// <summary>
        /// 最大客户端连接数量
        /// </summary>
        public int MaxAllowedOnlineUser
        {
            get { return maxAllowedOnlineUser; }
            set { maxAllowedOnlineUser = value; }
        }
    }
}


VerifyUserInfo类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UtilityClass
{
    /// <summary>
    /// 验证用户输入数据用的类
    /// </summary>
    public class VerifyUserInfo
    {
        /// <summary>
        /// 验证用户输入用户名的合法性
        /// </summary>
        /// <param name="name">输入名</param>
        /// <returns>结果</returns>
        public bool VerifyUserName(string name)
        {
            if (name!="")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 验证用户输入的IP知否正确
        /// </summary>
        /// <param name="ip">输入字符串</param>
        /// <returns>输出结果</returns>
        public bool VerifyServerIP(string ip)
        {
            if (ip=="")
            {
                return false;
            }
            else
            {
                string[] ipA = ip.Split('.');
                if (ipA.Length!=4)
                {
                    return false;
                }
                else
                {
                    int ip1, ip2, ip3, ip4;
                    try
                    {
                        ip1 = int.Parse(ipA[0]);
                        ip2 = int.Parse(ipA[1]);
                        ip3 = int.Parse(ipA[2]);
                        ip4 = int.Parse(ipA[3]);
                    }
                    catch (System.Exception ex)
                    {
                        return false;
                    }
                    if ((ip1>=0&&ip1<=255)&&(ip2>=0&&ip2<=255)&&(ip3>=0&&ip3<=255)&&(ip4>=0&&ip4<=255))
                    {
                        return true;
                    }
                    else 
                    {
                        return false;
                    }
                }
            }
        }


        /// <summary>
        /// 验证用户输入端口
        /// </summary>
        /// <param name="port">端口</param>
        /// <returns>结果</returns>
        public bool VerifyServerPort(string port)
        {
            if (port=="")
            {
                return false;
            }
            else
            {
                int port_int;
                try
                {
                    port_int = int.Parse(port);
                }
                catch (System.Exception ex)
                {
                    return false;
                }
                if (port_int>=1024&&port_int<=65535)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}


 

你可能感兴趣的:(socket,tcp,网络,String,聊天,工具)