一個簡易的聊天程式(Socket)

來源:互聯網
上載者:User

標籤:聊天   c#   網路編程   遠端連線   socket   

:



服務端Server代碼:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace Socket網路編程_Server{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void btnStart_Click(object sender, EventArgs e)        {            try            {                //當點擊開始監聽的時候 在伺服器端建立一個負責監IP地址跟連接埠號碼的Socket                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                IPAddress ip = IPAddress.Any;                //建立連接埠號碼對象                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));                //監聽                socketWatch.Bind(point);                ShowMsg("監聽成功");                socketWatch.Listen(10);                Thread th = new Thread(Listen);                th.IsBackground = true;                th.Start(socketWatch);            }            catch             { }                    }        /// <summary>        /// 等待用戶端的串連 並且建立與之通訊用的Socket        /// </summary>        Socket socketSend;        void Listen(Object o)//線程所執行的函數,如果有參數,必須是Object類型        {            Socket socketWatch = o as Socket;            //等待用戶端的串連 並且建立一個負責通訊的Socket            while (true)            {                try                {                    //負責跟用戶端通訊的Socket                    socketSend = socketWatch.Accept();                    //將遠端連線的用戶端的IP地址和Socket存入集合中                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(),socketSend);                    //將遠端連線的用戶端的IP地址和Socket存入到下拉框中                    cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());                    //192.168.11.87:串連成功                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":串連成功");                    //開啟一個新線程,不停的接收用戶端發來的訊息                    Thread th = new Thread(Recive);                    th.IsBackground = true;                    th.Start(socketSend);                }                catch                { }                            }        }        //將遠端連線的用戶端的IP地址和Socket存入集合中        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();        /// <summary>        /// 伺服器端不停的接收用戶端發來的訊息        /// </summary>        /// <param name="o"></param>        void Recive(Object o)        {            Socket socketSend = o as Socket;            while (true)            {                try                {                    //用戶端串連成功後,伺服器應該接受用戶端發來的資訊                    byte[] buffer = new byte[1024 * 1024 * 2];                    //實際接收到的有效位元組數                    int r = socketSend.Receive(buffer);                    if (r == 0)                    {                        break;                    }                    string str = Encoding.UTF8.GetString(buffer, 0, r);                    ShowMsg(socketSend.RemoteEndPoint + ":" + str);                }                catch                 { }            }        }        void ShowMsg(string str)        {            txtLog.AppendText(str + "\r\n");        }        private void Form1_Load(object sender, EventArgs e)        {            Control.CheckForIllegalCrossThreadCalls = false;        }        /// <summary>        /// 伺服器給用戶端發送訊息        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnSend_Click(object sender, EventArgs e)        {            try            {                string str = txtMsg.Text;                byte[] buffer = Encoding.UTF8.GetBytes(str);                List<byte> list = new List<byte>();                list.Add(0);                list.AddRange(buffer);                //將泛型集合轉換為集合                byte[] newBuffer = list.ToArray();                //獲得使用者在下拉框總選中的IP地址                string ip = cboUsers.SelectedItem.ToString();                dicSocket[ip].Send(newBuffer);                //socketSend.Send(buffer);            }            catch             {}                                }        /// <summary>        /// 選擇要發送的檔案        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnSelect_Click(object sender, EventArgs e)        {            OpenFileDialog ofd = new OpenFileDialog();            ofd.Title = "請選擇";            ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";            ofd.Filter = "所有檔案|*.*";            ofd.ShowDialog();            txtPath.Text = ofd.FileName;        }        private void btnSendFile_Click(object sender, EventArgs e)        {            //獲得要傳送檔案的路徑            string path = txtPath.Text;            using (FileStream fsRead=new FileStream(path,FileMode.Open,FileAccess.Read))            {                byte[] buffer = new byte[1024 * 1024 * 5];                int r = fsRead.Read(buffer, 0, buffer.Length);                List<byte> list = new List<byte>();                list.Add(1);                list.AddRange(buffer);                byte[] newBuffer = list.ToArray();                dicSocket[cboUsers.SelectedItem.ToString()].Send(newBuffer, 0, r+1, SocketFlags.None);            }        }        /// <summary>        /// 發送震動        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnZD_Click(object sender, EventArgs e)        {            byte[] buffer = new byte[1];            buffer[0] = 2;            dicSocket[cboUsers.SelectedItem.ToString()].Send(buffer);        }    }}

用戶端Client代碼:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace Socket網路編程_Client{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        Socket socketSend;        private void btnStart_Click(object sender, EventArgs e)        {            try            {                //建立負責通訊的Socket    1:表示IP v4     2:什麼類型的流,流氏的   3:對應的服務                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                //需要將文字框的IP地址轉換成IPAddress類型                IPAddress ip = IPAddress.Parse(txtServer.Text);                //需要將連接埠號碼轉換成IPEndPoint類型                  IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));                //獲得要串連的遠程伺服器應用程式的IP地址和連接埠號碼                socketSend.Connect(point);                ShowMsg("串連成功");                //開啟一個新的線程不停的接收伺服器端發來的訊息                Thread th = new Thread(Recive);                th.IsBackground = true;                th.Start();            }            catch { }        }        /// <summary>        /// 不停的接收伺服器發來的訊息        /// </summary>        void Recive()        {            while (true)            {                try                {                    byte[] buffer = new byte[1024 * 1024 * 3];                    //實際接收到的有效位元組數                    int r = socketSend.Receive(buffer);                    if (r == 0)                    {                        break;                    }                    //先拿到第一位,判斷髮送的是否文字訊息                    if (buffer[0] == 0)                    {                        //注意解碼的時候要從第一個開始到長度-1個位元組                        string s = Encoding.UTF8.GetString(buffer, 1, r-1);                        ShowMsg(socketSend.RemoteEndPoint + ":" + s);                    }                    if (buffer[0] == 1)                    {                        SaveFileDialog sfd = new SaveFileDialog();                        sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";                        sfd.Title = "請選擇要儲存的檔案";                        sfd.Filter = "所有檔案|*.*";                        sfd.ShowDialog(this);//不加this彈不出?                        string path = sfd.FileName;                        using (FileStream fsWrite=new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write))                        {                            fsWrite.Write(buffer,1,r-1);                        }                        MessageBox.Show("儲存成功 ");                    }                    if (buffer[0] == 2)                    {                        ZD();                    }                }                catch { }            }        }        /// <summary>        /// 震動        /// </summary>        void ZD()        {            for (int i = 0; i < 500; i++)            {                this.Location = new Point(200, 200);                this.Location = new Point(280,280);             }        }        void ShowMsg(string str)        {            txtLog.AppendText(str + "\r\n");        }        /// <summary>        /// 用戶端給伺服器發送訊息        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnSend_Click(object sender, EventArgs e)        {            string str = txtMsg.Text.Trim();            byte[] buffer = Encoding.UTF8.GetBytes(str);            socketSend.Send(buffer);        }        private void Form1_Load(object sender, EventArgs e)        {            Control.CheckForIllegalCrossThreadCalls = false;        }    }}


一個簡易的聊天程式(Socket)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.