Socket示例

服务端代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace SocketServerChatRoom
{
    public partial class FormServer : Form
    {
        public FormServer()
        {
            InitializeComponent();
        }

        private Socket tcpServer;
        private Dictionary<string, Socket> onlineList = new Dictionary<string, Socket>();
        private string CurrentTime
        {
            get
            {
                return DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
            }
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            string ip = this.txtIP.Text;
            int port = int.Parse(this.txtPort.Text);
            this.tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
            try
            {
                this.tcpServer.Bind(endPoint);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("服务器开启失败:{0}", ex.Message));
                return;
            }

            this.tcpServer.Listen(10);

            this.ShowMsg("服务器开启成功!");

            Task.Run(() => this.ListenConnection());

            this.btnStartServer.Enabled = false;

        }

        /// <summary>
        /// 监听连接
        /// </summary>
        private void ListenConnection()
        {
            while (true)
            {
                Socket tcpClient = this.tcpServer.Accept();
                string clientIP = tcpClient.RemoteEndPoint.ToString();

                this.AddOnLine(tcpClient, true);

                this.ShowMsg(clientIP + " 上线了!");

                Task.Run(() => this.ReceiveMsg(tcpClient));
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="tcpClient"></param>
        private void ReceiveMsg(Socket tcpClient)
        {
            while (true)
            {
                //定义2M的缓冲区
                byte[] buffer = new byte[1024 * 1024 * 2];
                int length = -1;
                try
                {
                    length = tcpClient.Receive(buffer);
                }
                catch
                {
                    this.AddOnLine(tcpClient, false);
                    break;
                }
                if (length == 0)
                {
                    this.AddOnLine(tcpClient, false);
                    break;
                }
                if (length > 0)
                {
                    string msg = Encoding.UTF8.GetString(buffer, 0, length).Trim();
                    this.ShowMsg(tcpClient.RemoteEndPoint.ToString() + "对你说:\r\n" + msg);
                }
            }
        }

        private void AddOnLine(Socket tcpClient, bool isAdd)
        {
            string clientIP = tcpClient.RemoteEndPoint.ToString();
            if (isAdd)
            {
                this.onlineList.Add(clientIP, tcpClient);
            }
            else
            {
                this.onlineList.Remove(clientIP);
            }
            Invoke(new Action(() =>
            {
                if (isAdd)
                {
                    this.listOnLine.Items.Add(clientIP);
                }
                else
                {
                    this.listOnLine.Items.Remove(clientIP);
                }
            }
            ));
        }

        private void ShowMsg(string msg)
        {
            Invoke(new Action(() =>
            {
                this.txtMsg.AppendText(this.CurrentTime + msg + Environment.NewLine);
            }
            ));
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            if (this.listOnLine.SelectedItems.Count > 0)
            {
                foreach (string item in this.listOnLine.SelectedItems)
                {
                    if (this.onlineList.ContainsKey(item))
                    {
                        this.onlineList[item].Send(Encoding.UTF8.GetBytes(this.txtSendMsg.Text));
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择要发送的对象!");
            }
        }

        private void btnSendMsgAll_Click(object sender, EventArgs e)
        {
            foreach (string item in this.listOnLine.Items)
            {
                if (this.onlineList.ContainsKey(item))
                {
                    this.onlineList[item].Send(Encoding.UTF8.GetBytes(this.txtSendMsg.Text));
                }
            }
        }

        private void btnClient_Click(object sender, EventArgs e)
        {
            FormClient formClient = new FormClient();
            formClient.Show();
        }
    }
}

客户端代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketServerChatRoom
{
    public partial class FormClient : Form
    {
        public FormClient()
        {
            InitializeComponent();
        }

        #region Socket-Client

        //创建Socket
        private Socket tcpClient;

        //创建取消数据源
        private CancellationTokenSource cts = new CancellationTokenSource();

        #region btnConnect_Click
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (this.btnConnect.Text == "连接")
            {
                string ip = this.txtIP.Text;
                int port = int.Parse(this.txtPort.Text);
                this.tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                EndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                try
                {
                    this.tcpClient.Connect(endPoint);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                this.btnConnect.Text = "断开";
                this.btnSendMsg.Enabled = true;

                Task.Run(new Action(() =>
                {
                    this.ReceiveMsg();
                }));

            }
            else
            {
                this.tcpClient?.Close();
                //this.cts.Cancel();
                this.btnConnect.Text = "连接";
                this.btnSendMsg.Enabled = false;
            }

        }
        #endregion

        #region ReceiveMsg
        private void ReceiveMsg()
        {
            while (!cts.IsCancellationRequested)
            {
                byte[] buffer = new byte[1024 * 10];
                int length = -1;
                try
                {
                    length = this.tcpClient.Receive(buffer, SocketFlags.None);
                }
                catch (Exception)
                {
                    break;
                }

                if (length > 0)
                {
                    string msg = Encoding.UTF8.GetString(buffer, 0, length).Trim();
                    this.txtMsg.Text += msg + "\r\n";
                }
            }
        }

        #endregion

        #endregion

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(this.txtMsg.Text);

            this.tcpClient.Send(buffer);
        }

        private void FormClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.cts.Cancel();
            if(this.tcpClient != null)
                this.tcpClient.Close();
        }
    }
}

 

posted on 2022-10-01 03:30  davidkam  阅读(50)  评论(0编辑  收藏  举报