用Socket实现客户端和服务器端通信(完整版)

Server:

public partial class MainForm : Form
    {

       //这里的PonySocket.Helper是我自定义的类,其中类中有Socket类型,string类型的属性,表示客户端连接的项,byte[]类型的属性,表示接收到的消息
        Dictionary<string,PonySocket.Helper> dicsoc = new Dictionary<string,PonySocket.Helper>();
       //timer判断是否有连接断开
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        int Port = 8000;    
        //定义一个委托,唤醒线程外控件的状态
        delegate void SetSaft(string text);

        ArrayList conList = new ArrayList();
        //确定编码
        Encoding UTF8 = Encoding.UTF8;
        Encoding GB2312 = Encoding.GetEncoding("GB2312");

        public MainForm()
        {
            InitializeComponent();
            this.timer.Interval = 2000;
            timer.Tick += new EventHandler(timer_Tick);
        }
      
        void timer_Tick(object sender, EventArgs e)
        {
            foreach (string key in dicsoc.Keys)
            {
                if (dicsoc[key].ChatSocket.Connected == false)
                {
                    DelList(dicsoc[key].Item);
                }
            }
        }   
        private void AddList(object text)
        {
            //判断对方控件是否调用了invoke方法
            if (this.listBox1.InvokeRequired)
            {
                SetSaft d = new SetSaft(AddList);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.listBox1.Items.Add(text);
            }
        }
        private void DelList(object text)
        {
            if (this.listBox1.InvokeRequired)
            {
                SetSaft d = new SetSaft(DelList);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.listBox1.Items.Remove(text);
            }
        }
        private void 开始服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.timer.Start();         
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint end = new IPEndPoint(IPAddress.Any, Port);
            socket.Bind(end);
            socket.Listen(10);//挂起连接队列的最大长度,根据操作系统而定
            socket.BeginAccept(new AsyncCallback(Accept), socket);
       
        }
        void Accept(IAsyncResult ar)
        {
            //获取用户定义的对象
            Socket socket = ar.AsyncState as Socket;
           //存储异步操作的信息,以及用户自定义的数据
            Socket worker = socket.EndAccept(ar);

            string serverEndpoint = "欢迎登录服务器:" + worker.LocalEndPoint.ToString();
            byte[] bgb = GB2312.GetBytes(serverEndpoint);
            byte[] buffer = Encoding.Convert(GB2312, UTF8, bgb);
            //发送给客户端
            worker.Send(buffer);

           //将客户端信息加在列表中
            string rpoint = worker.RemoteEndPoint.ToString();
            AddList(rpoint);

            PonySocket.Helper hh = new PonySocket.Helper(worker, buffer);
            dicsoc.Add(rpoint, hh);
            hh.Item = rpoint;          
        
            socket.BeginAccept(new AsyncCallback(Accept), socket);
            worker.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Receive), hh);
        }

        void Receive(IAsyncResult ar)
        {
            PonySocket.Helper h = ar.AsyncState as PonySocket.Helper;          
            try
            {
                int c = h.ChatSocket.EndReceive(ar);               
                h.ChatSocket.BeginReceive(h.MsgByte, 0, h.MsgByte.Length, SocketFlags.None, new AsyncCallback(Receive), h);

                string RemoPort= h.ChatSocket.RemoteEndPoint.ToString();
                string recivemsg = UTF8.GetString(h.MsgByte, 0, c);
            }
            catch
            {
               //nothing to do here!
            }
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (Socket o in conList)
                {
                    o.Shutdown(SocketShutdown.Both);
                    o.Close();
                }
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
            Application.Exit();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                foreach (Socket o in conList)
                {
                    o.Shutdown(SocketShutdown.Both);
                    o.Close();
                }           
            }
            catch(SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

客户端

public partial class MainForm : Form
    {
        Socket client = null;
        public string IP = null;//表示要连接的服务器IP
        private int Port = 8000;    

        Encoding UF8 = Encoding.UTF8;
        Encoding GB2312 = Encoding.GetEncoding("GB2312");
        delegate void SetSafe(string text);
      
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint end = new IPEndPoint(IPAddress.Parse("192.168.253.195"), Port);
            try
            {
                client.Connect(end);
                byte[] buffer = new byte[1024];
                PonySocket.Helper helper = new PonySocket.Helper(client, buffer);
                client.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,new AsyncCallback(Receive),helper);
                this.btnSend.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void Receive(IAsyncResult ar)
        {
            PonySocket.Helper h = ar.AsyncState as PonySocket.Helper;
            string ufstr = null;          
            try
            {
                int c = client.EndReceive(ar);
                //递归的接收数据
                h.ChatSocket.BeginReceive(h.MsgByte, 0, h.MsgByte.Length, SocketFlags.None, new AsyncCallback(Receive), h);
                ufstr = UF8.GetString(h.MsgByte, 0, c);
                SetText(ufstr);
            }
            catch
            {
                 ufstr = "服务器已经关闭或者其他原因导致连接不到服务器……";
                SetText(ufstr);
                this.btnSend.Enabled = false;
            }        
        }
        void SetText(string text)
        {
            //获取一个值,该值指示调用对控件进行方法调用时,必须调用Invoke方法,因为调用方位于控件线程以外的线程中
            if (this.label1.InvokeRequired)
            {
                SetSafe d = new SetSafe(SetText);
                this.label1.Invoke(d, new object[] { text });
            }
            else
            {
                this.label1.Text = text;
            }
        }

        private void SendMsg_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textBox1.Text))
            {
                byte[] buffer = UF8.GetBytes(this.textBox1.Text);
                PonySocket.Helper h = new PonySocket.Helper(client, buffer);
                client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendMsg), h);
            }
            else
            {
                MessageBox.Show("发送的内容不能为空!");
            }          
        }
        void SendMsg(IAsyncResult ar)
        {
            PonySocket.Helper h = ar.AsyncState as PonySocket.Helper;
            client.EndSend(ar);
        }
    }

你可能感兴趣的:(socket)