C# Socket通信客户端类、服务器类

         其实这些东西网上都有,但是比较凌乱,很少有封装好的类,在此共享一下。。。

         一个Socket服务器类,一个Socket客户端类,都可以直接拿去用,下边有详细的调用示例。

         需要说明的是,服务器类没有处理多客户连接,只是简单的响应单客户连接。

         另外,提醒一点,尤其是很多新手容易犯的错误,就是服务器类处理事务是在线程中进行的,此时不能访问界面上的控件,需要委托跨线程访问。

 

Socket服务器类(SocketServicesHelper.cs):


using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace USBControl
{
    /// <summary>
    /// Socket服务器类
    /// </summary>
    public class SocketServicesHelper
    {
        private Socket socket1 = null;
        private Socket socket2 = null;
        private Thread ListenThread = null;
        private int port = 0;  //监听端口
        
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="port">监听端口</param>
        public SocketServicesHelper(int port)
        {
            this.port = port;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        public void startServices() 
        {
            try
            {
                //获取本机IP
                IPAddress ip = IPAddress.Parse(getIP());
                //步骤1 创建网络端点IPEndPoint
                IPEndPoint myServer = new IPEndPoint(ip, port);
                //步骤2 创建套接字Socket
                socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //步骤3  套接字绑定到网络端点
                socket1.Bind(myServer);

                //创建监听线程
                ListenThread = new Thread(new ThreadStart(ListenFunction));
                //启动线程
                ListenThread.Start();
            }
            catch (Exception ex) 
            {
                throw ex;
            }
        }

        /// <summary>
        /// 监听方法,在线程中启动
        /// </summary>
        void ListenFunction()
        {
            try
            {
                clsUSBControl usbcl = new clsUSBControl();
                RegChangeNotice regChangeNotice = new RegChangeNotice();
                //步骤4  设置最大客户端连接数
                socket1.Listen(5);
                //循环检测客户端连接
                while (true)
                {
                    //步骤5  检测客户端连接
                    socket2 = socket1.Accept();
                    //步骤6  判断连接状态
                    if (socket2.Connected)
                    {
                        //步骤7 接收客户端消息
                        byte[] clientData = new byte[1024];
                        int i = socket2.Receive(clientData);
                        string removeMsg = Encoding.Unicode.GetString(clientData, 0, i).Split(new char[] { '|' })[0].Split(new char[] { ' ' })[1];

                        //根据消息做出相应动作



                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally 
            {
                //关闭连接
                if (socket1.Connected)
                {
                    socket1.Shutdown(SocketShutdown.Both);
                    socket1.Close();
                }
                if (socket2.Connected)
                {
                    socket2.Shutdown(SocketShutdown.Both);
                    socket2.Close();
                }
            }
        }

        /// <summary>  
        /// 获得本机IP地址
        /// </summary>  
        /// <returns></returns>
        private string getIP()
        {
            string ipAddress = "";
            Process p = null;
            StreamReader reader = null;
            try
            {
                ProcessStartInfo start = new ProcessStartInfo("cmd.exe");

                start.FileName = "ipconfig";
                start.Arguments = "/all";

                start.CreateNoWindow = true;

                start.RedirectStandardOutput = true;

                start.RedirectStandardInput = true;

                start.UseShellExecute = false;

                p = Process.Start(start);

                reader = p.StandardOutput;

                string line = reader.ReadLine();

                while (!reader.EndOfStream)
                {
                    if (line.ToLower().IndexOf("ip address") > 0 || line.ToLower().IndexOf("ipv4 地址") > 0 || line.ToLower().IndexOf("ip地址") > 0)
                    {
                        int index = line.IndexOf(":");
                        index += 2;
                        ipAddress = ipAddress + line.Substring(index) + ",";
                    }
                    line = reader.ReadLine();
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (p != null)
                {
                    p.WaitForExit();
                    p.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return Regex.Match(ipAddress.Equals("") ? ipAddress : ipAddress.Substring(0, ipAddress.Length - 1), "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}").ToString();
        }
    }
}


调用示例:

 

         //实例化时传入监听端口,本机IP自动获取

         SocketServicesHelper ssh = new SocketServicesHelper(8881);

         //开始监听

         ssh. startServices();



Socket 客户端类(SocketClientHelper.cs):



using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;


namespace BLL
{
    /// <summary>
    /// Socket客户端类
    /// </summary>
    public class SocketClientHelper
    {
        private IPAddress ip = null;
        private int port = 0;
        private Socket socket = null;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="ip">服务器IP</param>
        /// <param name="port">服务器端口</param>
        public SocketClientHelper(IPAddress ip, int port)
        {
            this.ip = ip;
            this.port = port;
        }

        /// <summary>
        /// 向服务器发送消息
        /// </summary>
        /// <param name="sendStr">消息内容</param>
        /// <returns></returns>
        public string send(string sendStr)
        {
            try
            {
                LayerParameter lp = new LayerParameter();

                IPEndPoint removeServer = new IPEndPoint(ip, port);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(removeServer);

                //检查连接状态
                if (socket.Connected)
                {
                    //转换编码
                    byte[] bs = Encoding.Unicode.GetBytes(sendStr);
                    //发送消息
                    socket.Send(bs, bs.Length, 0);

                    //断开SOCKET
                    socket.Shutdown(SocketShutdown.Both);

                    //关闭SOCKET
                    socket.Close();

                    return  "设置成功!";
                }
                else
                {
                    return "与客户端通信失败,可能是电脑未开启或者客户端未开启!";
                }
            }
            catch (Exception ex) 
            {
                throw ex;
            }
        }
    }
}


调用示例:

 

         //实例化时传入服务器IP和消息端口

         SocketClientHelper sch = new SocketClientHelper(IPAddress.Parse("192.168.24.177"),8881);

         //发送消息

         sch.send("Hello Word!");



posted @ 2012-11-28 17:00  杨元  阅读(5424)  评论(0编辑  收藏  举报