C # network socket data sending and receiving (using asynchronous) templates (modes)

Source: Internet
Author: User

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 );
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.