首页 > 作文

C#基于Socket套接字的网络通信封装

更新时间:2023-04-03 23:04:15 阅读: 评论:0

本文为大家分享了c#基于socket套接字的网络通信封装代码,供大家参考,具体内容如下

摘要

之所以要进行socket套接字通信库封装,主要是直接使用套接字进行网络通信编程相对复杂,特别对于初学者而言。实际上微软从.net 2.0开始已经提供了tcp、udp通信高级封装类如下:

tcplistener
tcpclient
udpclient

微软从.net 4.0开始提供基于task任务的异步通信接口。而直接使用socket封装库,很多socket本身的细节没办法自行控制,本文目就是提供一种socket的封装供参考。文中展示部分封装了tcp通信库,udp封装也可触类旁通:

custcplistener
custcpclient

tcp服务端

tcp服务端封装了服务端本地绑定、监听、接受客户端连接,并提供了网络数据流的接口。完整代码:

public class custcplistener    {        private ipendpoint mrversocketendpoint;        private socket mrversocket;        private bool isactive;         public socket rve从句是什么r        {            get { return this.mrversocket; }        }        protected bool active        {            get { return this.isactive; }        }        public endpoint localendpoint        {            get            {                if (!this.isactive)                {                    return this.mrversocketendpoint;                }                return this.mrversocket.localendpoint;            }        }        public networkstream datastream        {            get            {                networkstream networkstream = null;                if (this.rver.connected)                {                    networkstream = new networkstream(this.rver, true);                }                return networkstream;            }        }         public custcplistener(ipendpoint localep)        {            this.mrversocketendpoint = localep;            this.mrversocket = new socket(this.mrversocketendpoint.addressfamily, sockettype.stream, protocoltype.tcp);        }         public custcplistener(string localaddr, int port)        {            if (localaddr == null)            {                throw new argumentnullexception("localaddr");            }            this.mrversocketendpoint = new ipendpoint(ipaddress.par(localaddr), port);            this.mrversocket = new socket(this.mrversocketendpoint.addressfamily, sockettype.stream, protocoltype.tcp);        }         public custcplistener(int port)        {            this.mrversocketendpoint = new ipendpoint(ipaddress.any, port);            this.mrversocket = new socket(this.mrversocketendpoint.addressfamily, sockettype.stream, protocoltype.tcp);        }         public void start()        {            this.start(int.maxvalue);        }        /// <summary>        /// 开始服务器监听        /// </summary>        /// <param name="backlog">同时等待连接的最大个数(半连接队列个数限制)</param>        public void start(int backlog)        {            if (backlog > int.maxvalue || backlog < 0)            {                throw new argumentoutofrangeexception("backlog");            }            if (this.mrversocket == null)            {                throw new nullreferenceexception("套接字为空");            }            this.mrversocket.bind(this.mrversocketendpoint);            this.mrversocket.listen(backlog);            this.isactive = true;        }        public void stop()        {            if (this.mrversocket != null)            {                this.mrversocket.clo();                this.mrversocket = null;            }            this.isactive = fal;            this.mrversocket = new socket(this.mrversocketendpoint.addressfamily, sockettype.stream, protocoltype.tcp);        }         public socket acceptsocket()        {            socket socket = this.mrversocket.accept();            return socket;        }         public custcpclient accepttcpclient()        {            custcpclient tcpclient = new custcpclient(this.mrversocket.accept());            return tcpclient;        }    }

tcp客户端

tcp客户端封装了客户端本地绑定、连接服务器,并提供了网络数据流的接口。完整代码:

public class custcpclient : idisposable    {        public socket client { get; t; }        protected bool active { get; t; }        public ipendpoint clientsocketendpoint { get; t; }        public bool isconnected { get { return this.client.connected; } }        public networkstream datastream        {            get            {                networkstream networkstream = null;                if (this.client.connected)                {                    networ在一个kstream = new networkstream(this.client, true);                }                return networkstream;            }        }         public custcpclient(ipendpoint localep)        {            if (localep == null)            {                throw new argumentnullexception("localep");     描写星星的作文       }            this.client = new socket(localep.addressfamily, sockettype.stream, protocoltype.tcp);            this.active = fal;            this.client.bind(localep);            this.clientsocketendpoint = localep;        }         public custcpclient(string localaddr, int port)        {            if (localaddr == null)            {                throw new argumentnullexception("localaddr");            }            ipendpoint localep = new ipendpoint(ipaddress.par(localaddr), port);            this.client = new socket(localep.addressfamily, sockettype.stream, protocoltype.tcp);            this.active = fal;            this.client.bind(localep);            this.clientsocketendpoint = localep;        }        internal custcpclient(socket acceptedsocket)        {            this.client = acceptedsocket;            this.active = true;            this.clientsocketendpoint = (ipendpoint)this.client.localendpoint;        }         public void connect(string address, int 亲密的近义词port)        {            if (address == null)            {                throw new argumentnullexception("address");            }            ipendpoint remoteep = new ipendpoint(ipaddress.par(address), port);            this.connect(remoteep);        }         public void connect(ipendpoint remoteep)        {            if (remoteep == null)            {                throw new argumentnullexception("remoteep");            }            this.client.connect(remoteep);            this.active = true;        }         public void clo()        {            this.dispo(true);        }        protected virtual void dispo(bool disposing)        {            if (disposing)            {                idisposable datastream = this.datastream;                if (datastream != null)                {                    datastream.dispo();                }                el                {                    socket client = this.client;                    if (client != null)                    {                        client.clo();                        this.client = null;                    }                }                gc.suppressfinalize(this);            }        }         public void dispo()        {            this.dispo(true);        }    }

通信实验

控制台程序试验,服务端程序:

class program    {        static void main(string[] args)        {            thread listenerthread = new thread(listenerclientconnection);            listenerthread.isbackground = true;            listenerthread.start();             console.readkey();        }         private static void listenerclientconnection()        {            custcplistener tcplistener = new custcplistener("127.0.0.1", 5100);            tcplistener.start();            console.writeline("等待客户端连接……");            while (true)            {                custcpclient tcpclient = tcplistener.accepttcpclient();                 console.writeline("客户端接入,ip={0} port={1}",                    tcpclient.clientsocketendpoint.address, tcpclient.clientsocketendpoint.port);                thread thread = new thread(datahandleprocess);                thread.isbackground = true;                thread.start(tcpclient);            }   班级文化介绍     }         private static void datahandleprocess(object obj)        {            custcpclient tcpclient = (custcpclient)obj;            streamreader streamreader = new streamreader(tcpclient.datastream, encoding.default);            console.writeline("等待客户端输入:");            while (true)            {                try                {                    string recestr = streamreader.readline();                    console.writeline(recestr);                }                catch (exception)                {                    console.writeline("断开连接");                    break;                }                thread.sleep(5);            }        }    }

客户端程序:

class program    {        static void main(string[] args)        {            thread listenerthread = new thread(urprocess);            listenerthread.isbackground = true;            listenerthread.start();             console.readkey();        }         private static void urprocess()        {            console.writeline("连接服务器");            custcpclient tcpclient = new custcpclient("127.0.0.1", 5080);            tcpclient.connect("127.0.0.1", 5100);             console.writeline("开始和服务器通信");            streamwriter sw = new streamwriter(tcpclient.datastream, encoding.default);            sw.autoflush = true;            while (true)            {                for (int i = 0; i < 10; i++)                {                    string str = string.format("第{0}次,内容:{1}", i, "测试通信");                    console.writeline("发送数据:{0}", str);                    sw.writeline(str);                }                break;            }        }    }

通信成功:

通过本次封装演示可实现基于socket的通信库封装,目的就是使用socket通信库让应用开发人员在进行网络通讯编程时无需关心底层通讯机制,而只关心应用层的开发,让开发变得更简洁。当然udp封装类似,可自行设计。当然本文只是一种示例,实际使用可使用.net自带封装库或自定义封装。

补充:目前有很多优秀的开源socket框架,比如supersocketfastsocket等。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。

本文发布于:2023-04-03 23:04:13,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/46934cb0dd68912b6eea0353965167b8.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:C#基于Socket套接字的网络通信封装.doc

本文 PDF 下载地址:C#基于Socket套接字的网络通信封装.pdf

标签:通信   客户端   服务端   装了
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图