• TCP和UDP Client 代码


    最近学习要求做网络编程,使用从网上找了一些资料,主要是网络协议的分层等通讯,你可以查看英文版的资料:CScharp网络编程英文版

    下面直接给出代码吧,我想一看应该就懂。

    TCP Client 代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    namespace TcpLib
    {
        public class TcpClient
        {
    
            public TcpClient()
            {
                mSAEA.SetBuffer(new byte[1024 * 8], 0, 1024 * 8);
                mSAEA.Completed += Receive_Completed;
            }
    
            private bool mConnected = false;
    
            private Socket mSocket;
    
            private Exception mLastError;
    
            private SocketAsyncEventArgs mSAEA = new SocketAsyncEventArgs();
    
            public void DisConnect()
            {
                mConnected = false;
                try
                {
                    if (mSocket != null)
                    {
                        mSocket.Close();
                        
                    }
                }
                catch
                {
                }
                mSocket = null;
            }
    
            private void Receive_Completed(object sender, SocketAsyncEventArgs e)
            {
                try
                {
                    if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
                    {
                        TcpReceiveArgs tra = new TcpReceiveArgs();
                        tra.Data = e.Buffer;
                        tra.Offset = 0;
                        tra.Count = e.BytesTransferred;
                        OnReceive(tra);
                    }
                    else
                    {
                        mLastError = new SocketException((int)e.SocketError);
                        DisConnect();
                    }
                }
                catch (Exception e_)
                {
                    mLastError = e_;
                }
                finally
                {
                    BeginReceive();
                }
            }
    
            private void BeginReceive()
            {
                try
                {
                   
                    if (!mSocket.ReceiveAsync(mSAEA))
                    {
                        Receive_Completed(this, mSAEA);
                    }
                }
                catch (Exception e_)
                {
                    DisConnect();
                    mLastError = e_;
                }
               
                
            }
    
            protected virtual void OnReceive(TcpReceiveArgs e)
            {
                e.Client = this;
                if (Receive != null)
                    Receive(this, e);
            }
    
            public event EventHandler<TcpReceiveArgs> Receive;
    
            public Exception LastError
            {
                get
                {
                    return mLastError;
                }
            }
    
            public Socket Socket
            {
                get
                {
                    return mSocket;
                }
    
            }
    
            public bool Connected
            {
                get
                {
                    return mConnected;
                }
            }
    
            public void Connect(string host, int port)
            {
                IPAddress[] ips = Dns.GetHostAddresses(host);
                if(ips.Length ==0)
                    throw new Exception("get host's IPAddress error");
                var address = ips[0];
                try
                {
                    mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    mSocket.Connect(address, port);
                    mConnected = true;
                    BeginReceive();
                }
                catch (Exception e_)
                {
                    DisConnect();
                    mLastError = e_;
                    throw e_;
                }
            }
    
            public void Send(string value)
            {
                Send(value, Encoding.UTF8);
            }
    
            public void Send(string value, Encoding coding)
            {
                Send(coding.GetBytes(value));
            }
    
            public void Send(byte[] data)
            {
                Send(data, 0, data.Length);
            }
    
            public void Send(byte[] data, int offset, int count)
            {
                try
                {
                   
                    while (count > 0)
                    {
                        int sends = mSocket.Send(data, offset, count, SocketFlags.None);
                        count -= sends;
                        offset += sends;
                    }
                }
                catch (Exception e_)
                {
                    DisConnect();
                    mLastError = e_;
                    throw e_;
                }
            }
    
            public void Send(ArraySegment<byte> data)
            {
                Send(data.Array, data.Offset, data.Count);
    
    
            }
            
        }
    
        public class TcpReceiveArgs : EventArgs
        {
            public TcpClient Client
            {
                get;
                internal set;
            }
    
            public byte[] Data
            {
                get;
                internal set;
            }
    
            public int Offset
            {
                get;
                internal set;
            }
    
            public int Count
            {
                get;
                internal set;
            }
    
            public byte[] ToArray()
            {
                byte[] result = new byte[Count];
                Buffer.BlockCopy(Data, Offset, result, 0, Count);
                return result;
            }
    
            public void CopyTo(byte[] data, int start = 0)
            {
                Buffer.BlockCopy(Data, Offset, data, start, Count);
            }
        }
    
    }

    UDP Client 代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    namespace UdpLib
    {
        public class UdpClient
        {
            public UdpClient(string host, int port)
            {
                mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                if (string.IsNullOrEmpty(host))
                    mSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                else
                    mSocket.Bind(new IPEndPoint(IPAddress.Parse(host), port));
                mReceiveSAEA.Completed += OnReceiveCompleted;
                mReceiveSAEA.SetBuffer(new byte[1024 * 64], 0, 1024 * 64);
                BeginReceive();
            }
    
            private Exception mLastError;
    
            private SocketAsyncEventArgs mReceiveSAEA = new SocketAsyncEventArgs();
    
            private Socket mSocket;
    
            private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
            {
                try
                {
                    if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
                    {
                        UdpReceiveArgs ura = new UdpReceiveArgs();
                        ura.EndPoint = e.RemoteEndPoint;
                        ura.Data = e.Buffer;
                        ura.Offset = 0;
                        ura.Count = e.BytesTransferred;
                        OnReceive(ura);
                    }
                }
                catch (Exception e_)
                {
                    mLastError = e_;
                }
                finally
                {
                   
                    BeginReceive();
                }
            }
    
            private void BeginReceive()
            {
                IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
    
                mReceiveSAEA.RemoteEndPoint = endpoint;
                if (!mSocket.ReceiveFromAsync(mReceiveSAEA))
                {
                    OnReceiveCompleted(this, mReceiveSAEA);
                }
            }
    
            protected virtual void OnReceive(UdpReceiveArgs e)
            {
                if (Receive != null)
                    Receive(this, e);
            }
    
            public Exception LastError
            {
                get
                {
                    return mLastError;
                }
            }
    
            public void Send(string data, string host, int port)
            {
                Send(data, new IPEndPoint(IPAddress.Parse(host), port));
            }
    
            public void Send(byte[] data, string host, int port)
            {
                Send(data, new IPEndPoint(IPAddress.Parse(host), port));
            }
    
            public void Send(byte[] data, EndPoint point)
            {
                Send(data, 0, data.Length, point);
            }
            public void Send(byte[] data,int offset,int count, EndPoint point)
            {
                while (count > 0)
                {
                    int sends = mSocket.SendTo(data, offset, count, SocketFlags.None, point);
                    count -= sends;
                    offset += sends;
                }
            }
            public void Send(string data, EndPoint point)
            {
                Send(Encoding.UTF8.GetBytes(data), point);
            }
    
            public event EventHandler<UdpReceiveArgs> Receive;
    
        }
    
    
    
        public class UdpReceiveArgs : EventArgs
        {
    
            public EndPoint EndPoint
            {
                get;
                internal set;
            }
    
            public byte[] Data
            {
                get;
                internal set;
            }
    
            public int Offset
            {
                get;
                internal set;
            }
    
            public int Count
            {
                get;
                internal set;
            }
            public byte[] ToArray()
            {
                byte[] result = new byte[Count];
                Buffer.BlockCopy(Data, Offset, result, 0, Count);
                return result;
            }
    
            public void CopyTo(byte[] data, int start = 0)
            {
                Buffer.BlockCopy(Data, Offset, data, start, Count);
            }
        }
    
    }
  • 相关阅读:
    2018-3-8-WPF-UncommonField-类型是什么
    PHP mysqli_set_charset() 函数
    PHP mysqli_select_db() 函数
    PHP mysqli_rollback() 函数
    PHP mysqli_refresh() 函数
    PHP mysqli_real_escape_string() 函数
    使用Pam_Tally2锁定和解锁SSH失败的登录尝试
    MySQL的LIMIT与分页优化
    转mysql存储引擎memory,ndb,innodb之选择
    转mysql复制主从集群搭建
  • 原文地址:https://www.cnblogs.com/mq0036/p/3716146.html
Copyright © 2020-2023  润新知