Using system;
Using system. Collections. Generic;
Using system. text;
Using system. net. Sockets;
Using system. net;
Using system. Windows. forms;
Namespace socketclient
{
/// <Summary>
/// C # network socket data sending and receiving (using asynchronous) templates (modes)
/// </Summary>
Class test_socket
{
Socket m_socket;
/// <Summary>
/// C # data sending and receiving process of network socket (asynchronous)
/// </Summary>
/// <Param name = "_ IP"> IP address to connect </param>
/// <Param name = "_ port"> the port opened by the other Party </param>
Public void net_socket_send_receive (string _ IP, int _ port)
{
Ipendpoint ipep = new ipendpoint (IPaddress. parse (_ IP), _ port );
M_socket = new socket (ipep. addressfamily, sockettype. Stream, protocoltype. TCP );
Byte [] buffer = new byte [1024];
M_socket.beginsend (buffer, 0, buffer. length, socketflags. None, new asynccallback (onsend), null );
Byte [] recvbytes = new byte [20];
M_socket.beginreceive (recvbytes, 0, recvbytes. length, socketflags. None, new asynccallback (onreceive), null );
}
Private void onsend (iasyncresult AR)
{
Try
{
M_socket.endsend (AR );
}
Catch (objectdisposedexception)
{}
Catch (exception ex)
{
MessageBox. Show (ex. message, "Send:", messageboxbuttons. OK, messageboxicon. Error );
}
}
Private void onreceive (iasyncresult AR)
{
Try
{
M_socket.endreceive (AR );
}
Catch (objectdisposedexception)
{}
Catch (exception ex)
{
MessageBox. Show (ex. message, "receive:", messageboxbuttons. OK, messageboxicon. Error );
}
}
}
}