铭轩同学

铭轩,为自己代言!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

   利用晚上这点闲暇时间,写了一个Socket通信的小实例,该实例包含服务器端和客户端。其基本工作流程是:当服务器启动服务以后,客户端进行连接,如果连接成功,则用户可以在发送消息框中输入待发送的消息,然后点击“Send”按钮后向服务器发送消息,服务器在收到消息后立即向该客户端发送接收成功消息。其基本效果如图1.1和图1.2所示(注:下面两幅图于次日补上):

图1.1  服务器运行效果图

图1.2  客户端运行效果图

    现将服务器和客户端部分代码贴出来,由于代码较简单,基本没有注释,并在此特别说明,该实例仅仅是一个简单的示例,其中的代码仍有进一步修改优化空间,同时亦欢迎各位朋友批评指正。
    服务器代码部分:
using System;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketServer
{
    public partial class frmServer : Form
    {
        private Thread m_serverThread;
        private Socket m_serverSocket;
        private string m_serverIP;
        private int m_serverPort;

        public delegate void ReceiveMessageDelegate(Client client);
        ReceiveMessageDelegate receiveMessageDelegate;
        
        public frmServer()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void frmServer_Load(object sender, EventArgs e)
        {
            string[] addresses = GetLocalAddresses();
            cmbIP.Items.Clear();
            if (addresses.Length > 0)
            {
                for (int i = 0; i < addresses.Length; i++)
                {
                    cmbIP.Items.Add(addresses[i]);
                }
                cmbIP.Text = (string)cmbIP.Items[0];
            }

            txtPort.Text = "8899";
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            m_serverIP = cmbIP.Text;
            m_serverPort = Int32.Parse(txtPort.Text);

            Start();
            btnStart.Enabled = false;
            btnStop.Enabled = true;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Stop();
            btnStart.Enabled = true;
            btnStop.Enabled = false;
        }

        /// <summary>
        /// 开始服务
        /// </summary>
        private void Start()
        {
            try
            {
                m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(m_serverIP), m_serverPort);
                m_serverSocket.Bind(localEndPoint);
                m_serverSocket.Listen(10);

                m_serverThread = new Thread(new ThreadStart(ReceiveAccept));
                m_serverThread.Start();

                this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server started.");
            }
            catch (SocketException se)
            {
                throw new Exception(se.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        private void Stop()
        {
            try
            {
                m_serverThread.Abort(); // 线程终止
                m_serverSocket.Close(); // Socket Close

                this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server stoped.");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private void ReceiveAccept()
        {
            while (true)
            {
                Client client = new Client();

                try
                {
                    client.ClientSocket = m_serverSocket.Accept();
                    this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client[" + client.ClientSocket.RemoteEndPoint.ToString() + "] connected.");

                    receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages);
                    receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        private void ReceiveMessages(Client client)
        {
            while (true)
            {
                byte[] receiveBuffer = new byte[1024];

                client.ClientSocket.Receive(receiveBuffer);

                string strReceiveData = Encoding.Unicode.GetString(receiveBuffer);
                if (!string.IsNullOrEmpty(strReceiveData))
                {
                    this.AddRunningInfo(">> Receive data from [" + client.ClientSocket.RemoteEndPoint.ToString()+ "]:" + strReceiveData);
                    string strSendData = "OK. The content is:" + strReceiveData;
                    int sendBufferSize = Encoding.Unicode.GetByteCount(strSendData);
                    byte[] sendBuffer = new byte[sendBufferSize];
                    sendBuffer = Encoding.Unicode.GetBytes(strSendData);

                    client.ClientSocket.Send(sendBuffer);
                }
            }
        }

        private void ReceiveMessagesCallback(IAsyncResult AR)
        {
            receiveMessageDelegate.EndInvoke(AR);
        }

        /// <summary>
        /// 将运行信息加入显示列表
        /// </summary>
        private void AddRunningInfo(string message)
        {
            lstRunningInfo.BeginUpdate();
            lstRunningInfo.Items.Insert(0, message);

            if (lstRunningInfo.Items.Count > 100)
            {
                lstRunningInfo.Items.RemoveAt(100);
            }

            lstRunningInfo.EndUpdate();
        }

        /// <summary>
        /// 获取本机地址列表
        /// </summary>
        public string[] GetLocalAddresses()
        {
            // 获取主机名
            string strHostName = Dns.GetHostName();

            // 根据主机名进行查找
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);

            string[] retval = new string[iphostentry.AddressList.Length];

            int i = 0;
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                retval[i] = ipaddress.ToString();
                i++;
            }
            return retval;
        } 
    }

    /// <summary>
    /// 客户端会话信息类
    /// </summary>
    public class Client
    {
        Socket m_clientSocket;

        public Client() { }

        public Socket ClientSocket
        {
            get { return m_clientSocket; }
            set { this.m_clientSocket = value; }
        }
    }
}

    客户端部分:
using System;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;

namespace SocketClient
{
    public partial class frmClient : Form
    {
        private Socket m_clientSocket;
        private byte[] m_receiveBuffer = new byte[1024];

        public frmClient()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void frmClient_Load(object sender, EventArgs e)
        {
            txtIP.Text = "172.18.20.234";
            txtPort.Text = "8899";
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            string serverIP = txtIP.Text;
            int serverPort = Int32.Parse(txtPort.Text);

            m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIP),serverPort);

            try
            {
                m_clientSocket.Connect(remoteEndPoint);
                if (m_clientSocket.Connected)
                {
                    m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);

                    btnConnect.Enabled = false;
                    btnDisconnect.Enabled = true;

                    this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client connect server success.");
                }
            }
            catch (Exception)
            {
                this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client connect server fail.");
                m_clientSocket = null;
            }
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (m_clientSocket != null)
            {
                m_clientSocket.Close();

                btnConnect.Enabled = true;
                btnDisconnect.Enabled = false;
                btnSend.Enabled = false;

                this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client disconnected.");
            }
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        private void btnSend_Click(object sender, EventArgs e)
        {
            string strSendData = txtSend.Text;
            byte[] sendBuffer = new byte[1024];
            sendBuffer = Encoding.Unicode.GetBytes(strSendData);

            if (m_clientSocket != null)
            {
                m_clientSocket.Send(sendBuffer);
            }
        }

        private void ReceiveCallBack(IAsyncResult ar)
        {
            try
            {
                int REnd = m_clientSocket.EndReceive(ar);
                string strReceiveData = Encoding.Unicode.GetString(m_receiveBuffer, 0, REnd);
                this.HandleMessage(strReceiveData);
                m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 处理接收到的数据
        /// </summary>
        private void HandleMessage(string message)
        {
            message = message.Replace("/0", "");
            if (!string.IsNullOrEmpty(message))
            {
                this.AddRunningInfo(">> Receive Data from server:" + message);
            }
        }

        private void AddRunningInfo(string message)
        {
            lstRunningInfo.BeginUpdate();
            lstRunningInfo.Items.Insert(0, message);

            if (lstRunningInfo.Items.Count > 100)
            {
                lstRunningInfo.Items.RemoveAt(100);
            }

            lstRunningInfo.EndUpdate();
        }

        private void txtSend_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSend.Text) && m_clientSocket!=null)
            {
                btnSend.Enabled = true;
            }
            else
            {
                btnSend.Enabled = false;
            }
        }
    }
}

posted on 2014-10-11 15:15  铭轩同学  阅读(353)  评论(0编辑  收藏  举报