最近学习要求做网络编程,使用从网上找了一些资料,主要是网络协议的分层等通讯,你可以查看英文版的资料: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[ * ], , * );
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 > )
{
TcpReceiveArgs tra = new TcpReceiveArgs();
tra.Data = e.Buffer;
tra.Offset = ;
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 ==)
throw new Exception("get host's IPAddress error");
var address = ips[];
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, , data.Length);
} public void Send(byte[] data, int offset, int count)
{
try
{ while (count > )
{
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, , Count);
return result;
} public void CopyTo(byte[] data, int start = )
{
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[ * ], , * );
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 > )
{
UdpReceiveArgs ura = new UdpReceiveArgs();
ura.EndPoint = e.RemoteEndPoint;
ura.Data = e.Buffer;
ura.Offset = ;
ura.Count = e.BytesTransferred;
OnReceive(ura);
}
}
catch (Exception e_)
{
mLastError = e_;
}
finally
{ BeginReceive();
}
} private void BeginReceive()
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, ); 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, , data.Length, point);
}
public void Send(byte[] data,int offset,int count, EndPoint point)
{
while (count > )
{
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, , Count);
return result;
} public void CopyTo(byte[] data, int start = )
{
Buffer.BlockCopy(Data, Offset, data, start, Count);
}
} }
05-28 22:21