服务器代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ASYNServer
{
class Server
{
private TcpListener tcpListener;
byte[] buffer = new byte[8096];
public Server()
{
tcpListener = new TcpListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"),10001));
//开启侦听,最多只能连接20个客户端数目
tcpListener.Start(20);
tcpListener.BeginAcceptSocket(ClientConnect, tcpListener);
}
/// <summary>
/// 客户端连接
/// </summary>
/// <param name="ar"></param>
private void ClientConnect(IAsyncResult ar)
{
try
{
TcpListener listener = (TcpListener)ar.AsyncState;
Socket client = listener.EndAcceptSocket(ar);
Console.WriteLine(client.RemoteEndPoint.ToString() + "连接成功");
//侦听结束后开始接收数据
ReceiveData(client);
//重新侦听是否有新的客户端连接
//如果这里不写 那么只能侦听一次
tcpListener.BeginAcceptSocket(ClientConnect, tcpListener);
}
catch (Exception e)
{
Console.WriteLine("ClientConnect"+e.Message);
}
}
/// <summary>
/// 接受数据的回调
/// </summary>
/// <param name="client"></param>
private void ReceiveData(Socket client)
{
SocketError socketError;
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, out socketError, ReceiveCallback, client);
}
/// <summary>
/// 一次接收的数据的长度
/// </summary>
int receLen = 0;
private void ReceiveCallback(IAsyncResult ar)
{
try
{
SocketError socketError;
Socket client = (Socket)ar.AsyncState;
receLen = client.EndReceive(ar, out socketError);
if (receLen>0)
{
//处理接收到的数据
OnReceiveData(client);
}else//当receLen<=0的时候表示客户端断开和服务器的连接
{
Console.WriteLine(client.LocalEndPoint.ToString()+"关闭了");
}
//重新接受数据
ReceiveData(client);
}
catch (Exception e)
{
Console.WriteLine("ReceiveCallback:" + e.Message);
}
}
/// <summary>
/// 接受数据
/// </summary>
/// <param name="socket"></param>
private void OnReceiveData(Socket socket)
{
byte[] data = Encoding.UTF8.GetBytes("接受成功");
Console.WriteLine("来自客户端的数据是:"+Encoding.UTF8.GetString(buffer,0, receLen));
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="socket"></param>
/// <param name="data"></param>
public void SendData(Socket socket, byte[] data)
{
SocketError socketError;
socket.BeginSend(data, 0, data.Length, SocketFlags.None, out socketError, SendCallBack, socket);//异步发送数据
}
/// <summary>
/// 发送数据的回调
/// </summary>
/// <param name="ar"></param>
private void SendCallBack(IAsyncResult ar)
{
SocketError socketError;
Socket client = (Socket)ar.AsyncState;
client.EndSend(ar, out socketError);
}
}
}
客户端代码示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ASYNClient
{
class Client
{
private TcpClient tcpclient = null;
byte[] result;
public Client()
{
tcpclient = new TcpClient();
//连接服务器
tcpclient.BeginConnect(IPAddress.Parse("127.0.0.1"), 10001, ConnectCallback, tcpclient);
}
/// <summary>
/// 连接回调
/// </summary>
/// <param name="ar"></param>
private void ConnectCallback(IAsyncResult ar)
{
TcpClient client = (TcpClient)ar.AsyncState;
try
{
if (client.Connected)
{
//连接成功
client.EndConnect(ar);
//开始接受数据
ReceiveData(client);
}
}
catch (Exception e)
{
Console.WriteLine("ConnectCallback:"+e.Message);
}
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="client"></param>
private void ReceiveData(TcpClient client)
{
NetworkStream stream = client.GetStream();
result = new byte[client.Available];
try
{
stream.BeginRead(result, 0, result.Length, ReadCallBack, stream);
}
catch (Exception e)
{
Console.WriteLine("ReceiveData:"+e.Message );
}
}
/// <summary>
/// 接受消息回调
/// </summary>
/// <param name="ar"></param>
private void ReadCallBack(IAsyncResult ar)
{
NetworkStream stream;
try
{
stream = (NetworkStream)ar.AsyncState;
stream.EndRead(ar);
}
catch (IOException e)
{
Console.WriteLine("远程服务器关闭");
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="data"></param>
public void SendData(byte[] data)
{
if (tcpclient.Connected)
{
NetworkStream stream = tcpclient.GetStream();
stream.BeginWrite(data,0,data.Length, SendCallback, stream);
}
}
/// <summary>
/// 发送消息回调
/// </summary>
/// <param name="ar"></param>
private void SendCallback(IAsyncResult ar)
{
NetworkStream stream = (NetworkStream)ar.AsyncState;
stream.EndWrite(ar);
}
}
}