波斯马BOSSMA Information Technology

C#通信之Socket通信的简单例子

发布时间:2010年9月11日 / 分类:DOTNET / 21,929 次浏览 / 评论

socket通常也称作”套接字”,用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过”套接字”向网络发出请求或者应答网络请求。

这里构建一个简单的例子,客户端发消息,服务端接收,然后回执一条消息。大致能够了解如何使用Socket进行通信。

服务端监听,接收信息:

客户端连接,并发送信息:

使用Socket通信,程序一般会在幕后运行,然后再合适的时间提示信息。这很自然的就会涉及到多线程的问题。在这个例子中因为每个连接都要创建一个线程,所以需要对线程进行管理。这里我使用了两个类:Connection(管理具体Socket连接)和SocketListener(管理线程和连接)。

看看代码吧:

1、Connection:服务端用于接收消息,处理具体的连接

public class Connection
    {
        Socket _connection;

        public Connection(Socket socket)
        {
            _connection = socket;
        }

        public void WaitForSendData()
        {
            while (true)
            {
                byte[] bytes = new byte[1024];
                string data = "";

                //等待接收消息
                int bytesRec = this._connection.Receive(bytes);

                if (bytesRec == 0)
                {
                    ReceiveText("客户端[" + _connection.RemoteEndPoint.ToString() + "]连接关闭...");
                    break;
                }

                data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
                ReceiveText("收到消息:" + data);

                string sendStr = "服务端已经收到信息!";
                byte[] bs = Encoding.UTF8.GetBytes(sendStr);
                _connection.Send(bs, bs.Length, 0);
            }
        }

        public delegate void ReceiveTextHandler(string text);
        public event ReceiveTextHandler ReceiveTextEvent;
        private void ReceiveText(string text)
        {
            if (ReceiveTextEvent != null)
            {
                ReceiveTextEvent(text);
            }
        }
    }

2、SocketListener:启动服务端Socket监听

public class SocketListener
    {
        public Hashtable Connection = new Hashtable();

        public void StartListen()
        {
            try
            {
                //端口号、IP地址
                int port = 2000;
                string host = "127.0.0.1";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);

                //创建一个Socket类
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.Bind(ipe);//绑定2000端口
                s.Listen(0);//开始监听

                ReceiveText("启动Socket监听...");

                while (true)
                {
                    Socket connectionSocket = s.Accept();//为新建连接创建新的Socket

                    ReceiveText("客户端[" + connectionSocket.RemoteEndPoint.ToString() + "]连接已建立...");

                    Connection gpsCn = new Connection(connectionSocket);
                    gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText);

                    Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn);

                    //在新线程中启动新的socket连接,每个socket等待,并保持连接
                    Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData));
                    thread.Name = connectionSocket.RemoteEndPoint.ToString();
                    thread.Start();
                }
            }
            catch (ArgumentNullException ex1)
            {
                ReceiveText("ArgumentNullException:" + ex1);
            }
            catch (SocketException ex2)
            {
                ReceiveText("SocketException:" + ex2);
            }
        }

        public delegate void ReceiveTextHandler(string text);
        public event ReceiveTextHandler ReceiveTextEvent;
        private void ReceiveText(string text)
        {
            if (ReceiveTextEvent != null)
            {
                ReceiveTextEvent(text);
            }
        }
    }

3、服务端主程序

 /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SocketListener listener;
        public MainWindow()
        {
            InitializeComponent();

            InitServer();
        }

        private void InitServer()
        {
            System.Timers.Timer t = new System.Timers.Timer(2000);
            //实例化Timer类,设置间隔时间为5000毫秒;
            t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
            //到达时间的时候执行事件; 
            t.AutoReset = true;
            t.Start();
        }

        private void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (listener != null && listener.Connection != null)
            {
                //label2.Content = listener.Connection.Count.ToString();
                ShowText("连接数:" + listener.Connection.Count.ToString());
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(new ThreadStart(SocketListen));
            th.Start();
        }

        private void SocketListen()
        {
            listener = new SocketListener();
            listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
            listener.StartListen();
        }

        public delegate void ShowTextHandler(string text);
        ShowTextHandler setText;

        private void ShowText(string text)
        {
            if (System.Threading.Thread.CurrentThread != txtSocketInfo.Dispatcher.Thread)
            {
                if (setText == null)
                {
                    setText = new ShowTextHandler(ShowText);
                }
                txtSocketInfo.Dispatcher.BeginInvoke(setText, DispatcherPriority.Normal, new string[] { text });
            }
            else
            {
                txtSocketInfo.AppendText(text + "\n");
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ClientWindow client = new ClientWindow();
            client.Show();
        }
    }

4、客户端:建立连接,发送消息

 public partial class ClientWindow : Window
    {
        Socket c;
        public ClientWindow()
        {
            InitializeComponent();
            InitClient();
        }

        private void InitClient()
        {
            int port = 2000;
            string host = "127.0.0.1";
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
            c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket

            ShowText("连接到Socket服务端...");

            c.Connect(ipe);//连接到服务器
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowText("发送消息到服务端...");
                string sendStr = textBox2.Text;
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                c.Send(bs, bs.Length, 0);

                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);

                ShowText("服务器返回信息:" + recvStr);
            }
            catch (ArgumentNullException ex1)
            {
                Console.WriteLine("ArgumentNullException:{0}", ex1);
            }
            catch (SocketException ex2)
            {
                Console.WriteLine("SocketException:{0}", ex2);
            }
        }

        private void ShowText(string text)
        {
            txtSockInfo.AppendText(text + "\n");
        }
    }

这是一个WPF的程序,WPF对多线程访问控件和WinForm的处理方式不太一样。可以看看文中ShowText方法的处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自波斯马,原文地址《C#通信之Socket通信的简单例子

关键字:

建议订阅本站,及时阅读最新文章!
【上一篇】 【下一篇】

目前有3 条评论

  1. bossma 0楼:

    @xj
    抱歉,代码都发布出来了,时间长了原来的源码项目都找不到了。

  2. xj 0楼:

    能发个源码吗?502878532@qq.com

发表评论