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); } } }
关注我】。(●'◡'●)
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的【因为,我的写作热情也离不开您的肯定与支持,感谢您的阅读,我是【Jack_孟】!
本文来自博客园,作者:jack_Meng,转载请注明原文链接:https://www.cnblogs.com/mq0036/p/3716146.html
【免责声明】本文来自源于网络,如涉及版权或侵权问题,请及时联系我们,我们将第一时间删除或更改!
posted on 2014-05-08 14:39 jack_Meng 阅读(2380) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?