下面的代碼示例演示如何使用 SocketAsyncEventArgs 類在服務器和客戶端之間發送數據和接收響應
Server
using System
using System
using System
using System
namespace SocketTest
{
class Program
{
static void Main(string[] args)
{
Socket serverSk = new Socket(AddressFamily
serverSk
serverSk
SocketAsyncEventArgs AcceptSAE = new SocketAsyncEventArgs();
AcceptSAE
serverSk
Console
}
static void AcceptSAE_Completed(object sender
{
Socket serverSk = sender as Socket;
if (e
{
serverSk = e
SocketAsyncEventArgs SendSAE = new SocketAsyncEventArgs();
byte[] data = System
SendSAE
SendSAE
SocketAsyncEventArgs RecieveSAE = new SocketAsyncEventArgs();
byte[] buffer = new byte[
RecieveSAE
RecieveSAE
serverSk
serverSk
}
else
Console
}
static void RecieveSAE_Completed(object sender
{
Socket sk = sender as Socket;
byte[] data = e
string msg = System
Console
// sk
}
static void SendSAE_Completed(object sender
{
Socket sk = sender as Socket;
if (e
{
Console
byte[] data = e
string msg = System
Console
}
}
}
}
Cilent
using System
using System
using System
using System
namespace SocketTestTwo
{
class Program
{
static void Main(string[] args)
{
Socket clientSk = new Socket(AddressFamily
SocketAsyncEventArgs ConnectSAE = new SocketAsyncEventArgs();
ConnectSAE
ConnectSAE
clientSk
Console
}
static void ConnectSAE_Completed(object sender
{
Socket clientSk = sender as Socket;
if (e
{
SocketAsyncEventArgs SendSAE = new SocketAsyncEventArgs();
byte[] data = System
SendSAE
SendSAE
SocketAsyncEventArgs RecieveSAE = new SocketAsyncEventArgs();
byte[] buffer = new byte[
RecieveSAE
RecieveSAE
//先調用異步接收
clientSk
clientSk
}
}
static void RecieveSAE_Completed(object sender
{
Socket sk = sender as Socket;
byte[] data = e
string msg = System
Console
//sk
}
static void SendSAE_Completed(object sender
{
Socket sk = sender as Socket;
if (e
{
Console
}
}
}
}
先調試運行服務器項目
再調試運行客戶端項目
From:http://tw.wingwit.com/Article/program/net/201311/12699.html