当前位置: 代码网 > it编程>编程语言>Asp.net > C#编写Socket服务器

C#编写Socket服务器

2024年08月06日 Asp.net 我要评论
由Socket慨念,Socket一般应用模式,Socket的通讯过程,再逐步深入到项目界面设计,程序编码,叫你一步步实现用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 群发消息演示

源码地址:

如果你觉得我的分享有价值,那就请为我点赞收藏吧!你们的支持是我继续分享的动力。希望大家能够积极评论,让我知道你们的想法和建议。谢谢!
(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com