C# socket通信随记回顾

旧巷老猫 提交于 2019-12-10 02:26:42

----tcp(传输 控制 协议)是可靠消息:三次握手(发给对方,对方发给自己,证明对方接到消息,在发给对方,说明自己能接到对方消息,这样就都知道了):tcp:每发送一次消息,对方都会回复,证明接受到了所以是可靠地;包含许多校验,效率差;

---(UDP:用户 数据报 协议)数据报文服务:消息发送给对方就完事了,不管你是否接收到;

不可靠,但是效率高;

-----应用层协议:Http,Ftp,Popj SMTp

-----传输层:TCP,ICMP,UDP

-----网络层:IP,ARP ;

socket是应用层和传输层之间的交互;

---端口:三类:工人端口、注册端口、动态私有端口(这些可以用)

---套接字指的是socket;封装的网络插口;

----服务端:1创建socket,绑定端口和ip;打开监听,接受客户端;

----客户端:创建socket,链接服务器,创建ip端口,进行链接;

--服务器端接受科幻段消息时,创建socketProxy对象,占用系统自动分配的

一个端口,发送消息时重新占用新的端口,原来端口继续监听;

--说白了,监听端口收到消息创建新的socket对象,并绑定新的端口进行通信

--这个端口就帮死了,传递接受都用这一个端口),

而监听端口继续监听,

  public partial class Form1 : Form

    {

        List<Socket> list = new List<Socket>();

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

 

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            string ip = "192.168.1.1";

            //创建ip地址:

            IPAddress ipAddress = IPAddress.Parse(ip);

            //创建端口

            IPEndPoint ipPoint = new IPEndPoint(ipAddress, 3030);

            //穿点套接字:

            //参数1:寻址方式;参数2:socket传输方式:stream tcp方式,Dgram:数据报方式,第三个参数:协议

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //绑定端口和ip

            s.Bind(ipPoint);

            //开始监听:(请求最大连接长度),s为委托参数;

            ThreadPool.QueueUserWorkItem(new WaitCallback(Accept), s);

 

        }

        public void Accept(object obj)

        {

            Socket socket = (Socket)obj;

            while (true)

            {

                //接受客户端的一个连接创建代理套接字

                Socket proxys = socket.Accept();

                //存储这些通信管道;

                list.Add(proxys);

                //获取套接字端口和ip;

                // proxys.RemoteEndPoint.ToString();

                ThreadPool.QueueUserWorkItem(new WaitCallback(AcceptStarts), proxys);

            }

        }

        public void AcceptStarts(object obj)

        {

            Socket socket = (Socket)obj;

            while (true)

            {

                //通过判断异常来判断,是否客户端已中断,来关闭服务端的socket;

                try

                {

                    byte[] buffer = new byte[1024 * 1024];

                    int realLength = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);

                    string strResult = Encoding.Default.GetString(buffer, 0, buffer.Length);

                }

                catch

                {

                    socket.Close();

                    //异常已失效断开的socket;

                    list.Remove(socket);

                }

            }

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            //发送消息

            foreach (Socket s in list)

            {

                //防止socket断开失效;

                try

                {

                    string str = "发送内容";

                    byte[] bytes = Encoding.Default.GetBytes(str);

                    s.Send(bytes, SocketFlags.None);

                }

                catch

                {

                    s.Close();

                    //异常已失效断开的socket;

                    list.Remove(s);

                }

            }

        }

    }

--------------------客户端

 public partial class 客户端 : Form

    {

        public Socket CurrentSocket { get; set; }

        public 客户端()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            Socket socket =null;

            try

            {

                IPAddress ipAddress = IPAddress.Parse("192.168.1.1");

                IPEndPoint endpoint = new IPEndPoint(ipAddress, 8080);

                //创建socket;

                socket= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                socket.Connect(endpoint);

                CurrentSocket = socket;

            }

            catch

            {

                if (socket != null)

                {

                    socket.Dispose();

                }

            }

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            byte[] bytes = Encoding.Default.GetBytes("sdfsdfd");

            if (CurrentSocket != null)

            {

                try

                {

                    CurrentSocket.Send(bytes, 0, bytes.Length, 0);

                }

                catch

                {

                    CurrentSocket.Dispose();

                }

            }

        }

    }

socket传递的数据都是byte[]数组类型;

服务器端通过捕获异常来知道客户端关闭连接;

  Encoding.Default.GetBytes();

----503错误:访问人数过多

--------

-------------字节块拷贝: //字节块拷贝:

                byte[] a = new byte[1024];

                byte[] b = new byte[1025];

                b[0] =1;//这样可以说是自定义协议;第一个位代表什么意思;接受时根据第一个字节判断是传送的什么数据文件(比如1代表图片)

                Buffer.BlockCopy(a, 0, b,1,a.Length);

---魔鬼数字:1代表什么2代表什么,千万别使用,通常使用枚举;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!