最近想到要写写博客,那么就从2016的第一天开始吧。先写下c#中socket的异步编程吧,c#为socket提供了异步编程的接口我们就用这些写个自己的类吧
public class SocketWrapper
{
private static int len_buf;
byte[] buffer;
Socket commusocket = null;
string _ip = "";
int _port = 4531;
bool _connect = false;
ManualResetEvent Timeout = new ManualResetEvent(false);
public SocketWrapper(string ip,int port) //构造函数设定服务器的ip地址和端口
{
_ip = ip;
_port = port;
len_buf = 1024;
buffer = new byte[len_buf];
}
public bool Socket_Create_Connect()
{
commusocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint Serv = new IPEndPoint(IPAddress.Parse(_ip), _port);
Timeout.Reset();
try
{
commusocket.BeginConnect(Serv, new AsyncCallback(ConnectCallback), commusocket);//异步connect
}
catch(Exception exp)
{
StreamWriter mylog = new StreamWriter("log.txt", true); //记录日志文件
mylog.WriteLine(exp.Message + DateTime.Now.ToLocalTime().ToString());
mylog.Close();
return false;
}
if (Timeout.WaitOne(10000, false)) //这里等待10s或者是异步的回调函数调用Timeout.set()
{
if (_connect)
return true;
else
return false;
}
else
return false; //超时
}
public bool IsConnect
{
get { return _connect; }
set { _conne