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[ * ], , * );
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);
}
} }
TCP和UDP Client 代码的更多相关文章
- Linux 下socket通信终极指南(附TCP、UDP完整代码)
linux下用socket通信,有TCP.UDP两种协议,网上的很多教程把两个混在了一起,或者只讲其中一种.现在我把自己这两天研究的成果汇总下来,写了一个完整的,适合初学者参考,也方便自己以后查阅. ...
- 初识-----基于Socket的UDP和TCP编程及测试代码
一.概述 TCP(传输控制协议)和UDP(用户数据报协议是网络体系结构TCP/IP模型中传输层一层中的两个不同的通信协议. TCP:传输控制协议,一种面向连接的协议,给用户进程提供可靠的全双工的字节流 ...
- UDP client,UDP server, TCP server, TCP client
UDP server import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocke ...
- TCP/UDP Socket调试工具提供了TCP Server,TCP Client,UDP Server,UDP Client,UDP Group 五种Socket调试方案。
一.TCP通信测试: 1) 创建TCP Server: 选中左方的TCP Server, 然后点击”创建”按钮,软件弹出监听端口输入框 输入监听端口后,即创建了一个在指定端口上进行监听的TCP S ...
- [转]VB Winsock 控件TCP与UDP连接实例
[-] 可能的用途 选择通讯协议 协议的设置 确定计算机的名称 TCP 连接初步 接受多个连接请求 UDP 初步 关于 Bind 方法 利用 WinSock 控件可以与远程计算机建立连接,并通过用 ...
- Linux网络编程8——对TCP与UDP的简易封装
引言 每次使用socket通信,都会有很对相似的操作.本文,会对TCP与UDP通信做一简单封装,并生成动态库. 代码 my_socket.h #ifndef __MY_SOCKET_H__ #defi ...
- Android开发:如何实现TCP和UDP传输
TCP和UDP在网络传输中非常重要,在Android开发中同样重要. 首先来看一下什么是TCP和UDP. 什么是TCP? TCP:Transmission Control Protocol 传输控制协 ...
- 高性能 TCP & UDP 通信框架 HP-Socket v3.2.3 正式宣布
HP-Socket 是一套通用的高性能 TCP/UDP 通信框架,包括服务端组件.client组件和 Agent 组件.广泛适用于各种不同应用场景的 TCP/UDP 通信系统,提供 C/C++.C#. ...
- 高性能 TCP & UDP 通信框架 HP-Socket v3.2.2 正式公布
HP-Socket 是一套通用的高性能 TCP/UDP 通信框架,包括服务端组件.client组件和 Agent 组件,广泛适用于各种不同应用场景的 TCP/UDP 通信系统,提供 C/C++.C#. ...
随机推荐
- InFusion错误类型分析
1 God Class 1.1 特征 上帝类通常过多的操纵其他类的数据,从而破坏了类的封装性.上帝类从其他类中获得功能,同时增加了自身的耦合性,通常会导致自己具有规模过大和较高的复 ...
- ipod不识别命令
root@mx6q:~# history 0 sync 1 reboot 2 cd /usr/app/ 3 ls 4 cd extend-sysfs/ 5 ls 6 cd etc/ 7 ls 8 cd ...
- Linux的crontab
如果要让unix系统重复,定期做一件事,我们就会用到crontab. 实质上真正去执行每一个重复任务的是cron,cron是的unix家族的一个后台常驻程序,cron是由cron文件来驱动的,cron ...
- Log4js 工作原理及代码简析
本文地址 http://www.cnblogs.com/jasonxuli/p/6518650.html log4js 版本 0.6.16, 最新版1.1.1 大体类似. 使用 log4j ...
- ubuntu14.04安装CUDA8.0
ubuntu安装CUDA 因为深度学习需要用到CUDA,所以写篇博客,记录下自己安装CUDA 的过程. 1 安装前的检查 安装CUDA之前,首先要做一些事情,检查你的机器是否可以安装CUDA. 1.1 ...
- Tomcat 发布项目 conf/Catalina/localhost 配置 及数据源配置
本文介绍通过在tomcat的conf/Catalina/localhost目录下添加配置文件,来发布项目.因为这样对 tomcat 的入侵性最小,只需要新增一个配置文件,不需要修改原有配置:而且支持动 ...
- AOP Schema配置
AOP(Aspect-Oriented Programming,面向切面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入封装.继承和 ...
- Matlab绘图基础——利用axes(坐标系图形对象)绘制重叠图像 及 一图多轴(一幅图绘制多个坐标轴)
描述 axes在当前窗口中创建一个包含默认属性坐标系 axes('PropertyName',propertyvalue,...)创建坐标系时,同时指定它的一些属性,没有指定的使用DefaultAxe ...
- 视觉SLAM漫谈 (三): 研究点介绍
1. 前言 读者朋友们大家好!(很久很久)之前,我们为大家介绍了SLAM的基本概念和方法.相信大家对SLAM,应该有了基本的认识.在忙完一堆写论文.博士开题的事情之后,我准备回来继续填坑:为大家介绍S ...
- LINQ 学习路程 -- 查询操作 GroupBy ToLookUp
Grouping Operators Description GroupBy GroupBy操作返回根据一些键值进行分组,每组代表IGrouping<TKey,TElement>对象 To ...