1.socket.BeginConnect();
其中的三个参数值EndPoint remoteEP,这个是用来指定连接的socket服务器的的地址
EndPoint remoteEP | 这个的参数用来指定socket所连接的服务器的地址,一般包含的信息有,IP地址+端口号Point |
AsyncCallback callback | 这个参数指定一个异步的委托来请求socket服务器,并执行. |
objcet state | 用来指定异步请求委托的参数 |
public static void AsynConnect(string json, string ip, int port)
{
try
{
timeoutObject = new ManualResetEvent(false);
sendstr = json;
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port);
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.BeginConnect(ipe, new AsyncCallback(CallBackMethod), client); if (!timeoutObject.WaitOne(, false))
{
client.Close();
}
}
catch (Exception ex)
{ }
} public static void CallBackMethod(IAsyncResult asyncresult)
{
try
{
client = asyncresult.AsyncState as Socket;
if (client != null)
{
client.EndConnect(asyncresult);
AsynSend(client, sendstr);
AsynRecive(client); }
}
catch (Exception e)
{ }
finally
{
timeoutObject.Set();
}
} public static void AsynSend(Socket socket, string message)
{
if (socket == null || message == string.Empty) return;
//编码
byte[] data = Encoding.UTF8.GetBytes(message);
try
{
socket.BeginSend(data, , data.Length, SocketFlags.None, asyncResult =>
{
int length = socket.EndSend(asyncResult);
// Console.WriteLine(string.Format("客户端发送消息:{0}", message));
}, null);
}
catch (Exception ex)
{ }
} static string receicestr = ""; public static void AsynRecive(Socket socket)
{
byte[] data = new byte[];
try
{ socket.BeginReceive(data, , data.Length, SocketFlags.None,
asyncResult =>
{
int length = socket.EndReceive(asyncResult);
receicestr += Encoding.UTF8.GetString(data);
AsynRecive(socket);
}, null);
}
catch (Exception ex)
{ }
}
按照我的理解是,先创建一个socket连接对象,开启BeginConnect()连接的同时,开启一个新的线程用来走
传入的异步委托,在委托中调用EndConnect(),方法来来让阻塞的线程往下走并同时进行了发送消息和接受
消息两个操作,
第一篇随笔可能语言逻辑和信息不太完整和严谨,如果有错误的地方和不严谨的地方请在下方回复我,我将及时改正