C#编写Socket服务器

1.Socket介绍

所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议栈进行交互的接口 

2.Socket一般应用模式(服务器端和客户端)

3.Socket的通讯过程

4.Socket通信基本流程图:

5.项目界面设计

6.实现核心代码

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 TCPProgect
{
    public partial class FrmServer : Form
    {
        public FrmServer()
        {
            InitializeComponent();
        }

       
        //第一步:调用socket()函数创建一个用于通信的套接字
        private Socket listenSocket;

        //字典集合:存储IP和Socket的集合
        private Dictionary<string, Socket> OnLineList = new Dictionary<string, Socket>();

        //当前时间
        private string CurrentTime
        {
            get { return DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine; }
        }

        //编码格式
        Encoding econding = Encoding.Default;


        private void btn_StartService_Click(object sender, EventArgs e)
        {
            //第一步:调用socket()函数创建一个用于通信的套接字
            listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //第二步:给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用Bind()函数来实现
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(this.txt_IP.Text.Trim()), int.Parse(this.txt_Port.Text.Trim()));

            try
            {
                listenSocket.Bind(endPoint);
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务器开启失败:" + ex.Message, "开启服务器");
                return;
            }

            //第三步:调用listen()函数使套接字成为一个监听套接字
            listenSocket.Listen(10);

            ShowMessage("服务器开启成功");

            //开启一个线程监听
            Task.Run(new Action(() =>
                {
                    ListenConnection();
                }
                ));

            this.btn_StartService.Enabled = false;


        }

        private void ListenConnection()
        {
            while (true)
            {
                Socket clientSocket = listenSocket.Accept();

                string ip = clientSocket.RemoteEndPoint.ToString();

                //更新在线列表
                AddOnLine(ip, true);
                //更新在线列表集合
                OnLineList.Add(ip, clientSocket);

                ShowMessage(ip + "上线了");

                Task.Run(() => ReceiveMsg(clientSocket));

            }


        }


        /// <summary>
        /// 接收方法
        /// </summary>
        /// <param name="clientSocket"></param>
        private void ReceiveMsg(Socket clientSocket)
        {
            while (true)
            {
                //定义一个2M的缓冲区
                byte[] buffer = new byte[1024 * 1024 * 2];

                int length = -1;
                try
                {
                    length = clientSocket.Receive(buffer);
                }
                catch (Exception)
                {

                    //客户端下线了

                    //更新在线列表
                    string ip = clientSocket.RemoteEndPoint.ToString();

                    AddOnLine(ip, false);

                    OnLineList.Remove(ip);

                    break;
                }

                if (length == 0)
                {
                    //客户端下线了

                    //更新在线列表
                    string ip = clientSocket.RemoteEndPoint.ToString();

                    AddOnLine(ip, false);

                    OnLineList.Remove(ip);

                    break;
                }


                if (length > 0)
                {
                    string info = econding.GetString(buffer, 0, length);
                    ShowMessage(info);
                }
            }
        }

        /// <summary>
        /// 在线列表更新
        /// </summary>
        /// <param name="clientIp"></param>
        /// <param name="value"></param>
        private void AddOnLine(string clientIp, bool value)
        {
            Invoke(new Action(() =>
            {
                if (value)
                {
                    this.lst_Online.Items.Add(clientIp);
                }
                else
                {
                    this.lst_Online.Items.Remove(clientIp);
                }

            }));

        }


        /// <summary>
        /// 更新接收区
        /// </summary>
        /// <param name="info"></param>
        private void ShowMessage(string info)
        {
            Invoke(new Action(() =>
            {
                this.txt_Rcv.AppendText(CurrentTime + info + Environment.NewLine);
            }));

        }

        /// <summary>
        /// 消息发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Send_Click(object sender, EventArgs e)
        {
            if (this.lst_Online.SelectedItem != null)
            {
                foreach (string item in this.lst_Online.SelectedItems)
                {
                    if (OnLineList.ContainsKey(item))
                    {
                        OnLineList[item].Send(econding.GetBytes(this.txt_Send.Text.Trim()));
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择要发送的对象", "发送消息");
            }

        }

        /// <summary>
        /// 群发功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendAll_Click(object sender, EventArgs e)
        {
            foreach (string item in this.lst_Online.Items)
            {
                if (OnLineList.ContainsKey(item))
                {
                    OnLineList[item].Send(econding.GetBytes(this.txt_Send.Text.Trim()));
                }
            }
        }
    }
}

7.运行效果

        7.1 运行界面演示

         7.2 接收消息界面演示

         7.3 发送消息界面演示

         7.4 群发消息演示

源码地址:https://download.csdn.net/download/m0_73500215/89143273

如果你觉得我的分享有价值,那就请为我点赞收藏吧!你们的支持是我继续分享的动力。希望大家能够积极评论,让我知道你们的想法和建议。谢谢!
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,您需要编写一个 C# 客户端程序,通过多线程实现连接服务器的功能,对吧? 那么,您可以使用 C# 中的 Socket 类来实现客户端和服务器之间的通信。具体步骤如下: 1. 创建一个 Socket 对象,指定连接的服务器IP 和端口号。 ``` Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAddress = IPAddress.Parse(serverIP); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, serverPort); ``` 2. 使用 Socket 对象的 Connect 方法连接服务器。 ``` clientSocket.Connect(ipEndPoint); ``` 3. 在一个单独的线程中,使用 Socket 对象的 Send 和 Receive 方法进行数据的发送和接收。如果需要保持连接,可以在一个循环中执行 Send 和 Receive 方法。 ``` Thread sendThread = new Thread(() => { while (true) { // 发送数据 byte[] sendData = Encoding.UTF8.GetBytes("Hello, Server!"); clientSocket.Send(sendData); Thread.Sleep(1000); } }); Thread receiveThread = new Thread(() => { while (true) { // 接收数据 byte[] receiveData = new byte[1024]; int receiveLength = clientSocket.Receive(receiveData); string receiveMessage = Encoding.UTF8.GetString(receiveData, 0, receiveLength); Console.WriteLine("Received message from server: {0}", receiveMessage); } }); sendThread.Start(); receiveThread.Start(); ``` 4. 当需要关闭连接时,调用 Socket 对象的 Close 方法关闭连接。 ``` clientSocket.Close(); ``` 注意,以上代码仅为示例代码,实际应用中需要进行适当的异常处理和错误处理。同时,为了保证代码的健壮性和可维护性,您也可以使用 .NET Framework 中提供的异步方法来实现客户端和服务器之间的通信。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值