本文整理汇总了C#中System.Net.Sockets.SocketAsyncEventArgs类的典型用法代码示例。如果您正苦于以下问题:C# SocketAsyncEventArgs类的具体用法?C# SocketAsyncEventArgs怎么用?C# SocketAsyncEventArgs使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SocketAsyncEventArgs类属于System.Net.Sockets命名空间,在下文中一共展示了SocketAsyncEventArgs类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Listener
public Listener(IPEndPoint ipep)
{
m_Accepted = new Queue<Socket>();
m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot;
m_Listener = Bind(ipep);
if (m_Listener == null)
{
return;
}
DisplayListener();
#if NewAsyncSockets
m_EventArgs = new SocketAsyncEventArgs();
m_EventArgs.Completed += new EventHandler<SocketAsyncEventArgs>( Accept_Completion );
Accept_Start();
#else
m_OnAccept = OnAccept;
try
{
IAsyncResult res = m_Listener.BeginAccept(m_OnAccept, m_Listener);
}
catch (SocketException ex)
{
NetState.TraceException(ex);
}
catch (ObjectDisposedException)
{ }
#endif
}
开发者ID:Crome696,项目名称:ServUO,代码行数:32,代码来源:Listener.cs
示例2: ServerConnection
/// <summary>
/// A connection to our server, always listening asynchronously.
/// </summary>
/// <param name="socket">The Socket for the connection.</param>
/// <param name="args">The SocketAsyncEventArgs for asyncronous recieves.</param>
/// <param name="dataReceived">A callback invoked when data is recieved.</param>
/// <param name="disconnectedCallback">A callback invoked on disconnection.</param>
public ServerConnection(Socket socket, SocketAsyncEventArgs args, DataReceivedCallback dataReceived,
DisconnectedCallback disconnectedCallback)
{
logger = new ElibLogging("data");
this.AuthorizationType = Securtiy.AuthorizationType.Anonymous;
lock (this)
{
var remotIP = socket.RemoteEndPoint as IPEndPoint;
var localIP = socket.LocalEndPoint as IPEndPoint;
State state = new State()
{
socket = socket,
dataReceived = dataReceived,
disconnectedCallback = disconnectedCallback,
Device = new Device()
{
RemoteIP = remotIP.Address.ToString(),
LocalIP = localIP.Address.ToString()
}
};
eventArgs = args;
eventArgs.Completed += ReceivedCompleted;
eventArgs.UserToken = state;
ListenForData(eventArgs);
}
}
开发者ID:kainhong,项目名称:CurrencyStore,代码行数:35,代码来源:ServerConnection.cs
示例3: Init
// Initializes the server by preallocating reusable buffers and
// context objects. These objects do not need to be preallocated
// or reused, but it is done this way to illustrate how the API can
// easily be used to create reusable objects to increase server performance.
//
public void Init()
{
// Allocates one large byte buffer which all I/O operations use a piece of. This gaurds
// against memory fragmentation
m_bufferManager.InitBuffer();
// preallocate pool of SocketAsyncEventArgs objects
SocketAsyncEventArgs readWriteEventArg;
for (int i = 0; i < m_numConnections; i++)
{
//Pre-allocate a set of reusable SocketAsyncEventArgs
readWriteEventArg = new SocketAsyncEventArgs();
readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
readWriteEventArg.UserToken = new AsyncUserToken();
//((AsyncUserToken) readWriteEventArg.UserToken).name = "e" + i;
// assign a byte buffer from the buffer pool to the SocketAsyncEventArg object
m_bufferManager.SetBuffer(readWriteEventArg);
// add SocketAsyncEventArg to the pool
m_readWritePool.Push(readWriteEventArg);
}
}
开发者ID:vls,项目名称:hp2p,代码行数:30,代码来源:Server.cs
示例4: StartConnectAsync
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
{
lock (lockObject)
{
GlobalLog.Assert(endPoint.AddressFamily == AddressFamily.Unspecified ||
endPoint.AddressFamily == AddressFamily.InterNetwork ||
endPoint.AddressFamily == AddressFamily.InterNetworkV6,
"MultipleConnectAsync.StartConnectAsync(): Unexpected endpoint address family - " + endPoint.AddressFamily.ToString());
this.userArgs = args;
this.endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (state == State.Canceled)
{
SyncFail(new SocketException(SocketError.OperationAborted));
return false;
}
GlobalLog.Assert(state == State.NotStarted, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
state = State.DnsQuery;
IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.CompletedSynchronously)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
开发者ID:REALTOBIZ,项目名称:mono,代码行数:37,代码来源:_MultipleConnectAsync.cs
示例5: ConnectTo
public void ConnectTo(string ip, int port)
{
State = ConnectionState.NotConnected;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress[] ips = Dns.GetHostAddresses(ip);
var addr = ips[0];
var hostEndPoint = new IPEndPoint(addr, port);
var connectEA = new SocketAsyncEventArgs();
connectEA.RemoteEndPoint = hostEndPoint;
connectEA.Completed += (object sender, SocketAsyncEventArgs e)=>{
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
UnityEngine.Debug.Log("Connect success");
break;
default:
throw new ArgumentException("The last operation completed on the socket was not a receive or send");
}
connectEA.Dispose();
State = ConnectionState.Connected;
};
State = ConnectionState.Connecting;
socket.ConnectAsync(connectEA);
}
开发者ID:xclouder,项目名称:godbattle,代码行数:35,代码来源:NetworkInterface.cs
示例6: Accept_Completed
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
e.Completed -= Accept_Completed;
if (e.SocketError != SocketError.Success)
{
var error = string.Format("There was an error accepting a socket connection ({0}).",
Enum.GetName(typeof(SocketError), e.SocketError));
OnConnectionAccepted(new ConnectionAcceptedEventArgs(error));
return;
}
var clientConnection = new ClientConnection(e.AcceptSocket);
try
{
OnConnectionAccepted(new ConnectionAcceptedEventArgs(clientConnection));
clientConnection.ShutdownAndClose();
}
finally
{
((IDisposable)clientConnection).Dispose();
}
OnConnectionClosed();
AcceptIncomingConnection();
}
开发者ID:jprice628,项目名称:Sketch,代码行数:26,代码来源:ConnectionListener.cs
示例7: InitializeAsync
internal async Task InitializeAsync()
{
await Task.Run(() =>
{
var args = new SocketAsyncEventArgs
{
UserToken = _socket,
RemoteEndPoint = _endPoint
};
args.Completed += async (sender, eventArgs) =>
{
if (((Socket)sender).Connected)
{
_isConnected = true;
await _display.WriteAsync("NTRIP Connected");
await Task.Delay(500);
}
else
{
_isConnected = false;
await _display.WriteAsync("NTRIP Connection failed");
}
};
_socket.ConnectAsync(args);
}).ConfigureAwait(false);
}
开发者ID:Slimordium,项目名称:Hexapi_Hexapod,代码行数:31,代码来源:NtripClient.cs
示例8: BufferPool_CheckIn_Resets_SocketArg_Data_Buffer
public void BufferPool_CheckIn_Resets_SocketArg_Data_Buffer()
{
var socketArg = new SocketAsyncEventArgs();
BufferPool.Instance.CheckOut(socketArg);
BufferPool.Instance.CheckIn(socketArg);
Assert.IsNull(socketArg.Buffer);
}
开发者ID:luuksommers,项目名称:oswos,代码行数:7,代码来源:BufferPoolTests.cs
示例9: UdpSocketWrapper
/// <summary>
/// Initializes a new instance of the <see cref="UdpSocketWrapper"/> class.
/// </summary>
public UdpSocketWrapper()
{
// operation arguments
var args = new SocketAsyncEventArgs();
args.Completed += SocketAsyncEventArgs_Completed;
_socketOperation = args;
}
开发者ID:porter1130,项目名称:WP8-DEMO,代码行数:10,代码来源:UdpSocketWrapper.cs
示例10: SocketAsyncEventArgsProxy
public SocketAsyncEventArgsProxy(SocketAsyncEventArgs socketEventArgs, bool isRecyclable)
{
SocketEventArgs = socketEventArgs;
OrigOffset = socketEventArgs.Offset;
SocketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArgs_Completed);
IsRecyclable = isRecyclable;
}
开发者ID:huamanhtuyen,项目名称:TagLo2,代码行数:7,代码来源:SocketAsyncEventArgsProxy.cs
示例11: SocketAsyncEventArgsDecorator
public SocketAsyncEventArgsDecorator(SocketAsyncEventArgs socketAsyncEventArgs)
{
if (socketAsyncEventArgs == null)
throw new ArgumentNullException("socketAsyncEventArgs");
this.socketAsyncEventArgs = socketAsyncEventArgs;
}
开发者ID:vgrigoriu,项目名称:Redis.SilverlightClient,代码行数:7,代码来源:SocketAsyncEventArgsDecorator.cs
示例12: AllocNewAsyncArgs
SocketAsyncEventArgs AllocNewAsyncArgs()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += m_receiveCompleteHandler;
return args;
}
开发者ID:DM-TOR,项目名称:nhin-d,代码行数:7,代码来源:UdpServer.cs
示例13: OnEvent
public override bool OnEvent(SocketAsyncEventArgs e)
{
if (Protocol.IsEnqueueForDelete || Protocol.TimePeriodElapsed()) return true;
Logger.FATAL("Unable to handle TimeElapsed event");
IOHandlerManager.EnqueueForDelete(this);
return false;
}
开发者ID:langhuihui,项目名称:csharprtmp,代码行数:7,代码来源:IOTimer.cs
示例14: Accept_Completed
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = e.AcceptSocket;
Console.WriteLine("Accepting connection");
byte[] bytesFrom = new byte[LENGTH.MAX_PACKET_LEN];
string dataFromClient = null;
ClientSocket.Receive(bytesFrom);
dataFromClient = System.Text.Encoding.UTF8.GetString(bytesFrom);
ChatProtocol chatProtocol = JsonConvert.DeserializeObject<ChatProtocol>(dataFromClient);
socketToClient.Add(ClientSocket, chatProtocol.sender_id);
clientToSocket.Add(chatProtocol.sender_id, ClientSocket);
Console.WriteLine(chatProtocol.sender_id + " Joined ");
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
szData = new byte[1024];
args.SetBuffer(szData, 0, 1024);
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
ClientSocket.ReceiveAsync(args);
e.AcceptSocket = null;
m_ServerSocket.AcceptAsync(e);
}
开发者ID:yguhan,项目名称:SmileWorld,代码行数:26,代码来源:Program.cs
示例15: TcpChannel
/// <summary>
/// Initializes a new instance of the <see cref="TcpChannel" /> class.
/// </summary>
/// <param name="readBuffer">Buffer used for our reading.</param>
/// <param name="encoder">Used to encode messages before they are put in the MicroMessage body of outbound messages.</param>
/// <param name="decoder">
/// Used to decode the body of incoming MicroMessages. The <c>MessageReceived</c> delegate will be
/// overridden by this class.
/// </param>
public TcpChannel(IBufferSlice readBuffer, IMessageEncoder encoder, IMessageDecoder decoder) {
if (readBuffer == null) throw new ArgumentNullException("readBuffer");
if (encoder == null) throw new ArgumentNullException("encoder");
if (decoder == null) throw new ArgumentNullException("decoder");
_readArgs = new SocketAsyncEventArgs();
_readArgs.SetBuffer(readBuffer.Buffer, readBuffer.Offset, readBuffer.Capacity);
_readArgs.Completed += OnReadCompleted;
_readArgsWrapper = new SocketAsyncEventArgsWrapper(_readArgs);
_encoder = encoder;
_decoder = decoder;
_decoder.MessageReceived = OnMessageReceived;
_writeArgs = new SocketAsyncEventArgs();
_writeArgs.Completed += OnSendCompleted;
_writeArgsWrapper = new SocketAsyncEventArgsWrapper(_writeArgs);
_sendCompleteAction = (channel, message) => { };
_disconnectAction = (channel, exception) => { };
ChannelFailure = (channel, error) => HandleDisconnect(SocketError.ProtocolNotSupported);
RemoteEndpoint = EmptyEndpoint.Instance;
ChannelId = GuidFactory.Create().ToString();
Data = new ChannelData();
}
开发者ID:Tochemey,项目名称:NetFreeSwitch.Framework,代码行数:35,代码来源:TcpChannel.cs
示例16: Start
/// <summary>
/// 启动监听
/// </summary>
/// <param name="config">服务器配置</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
m_ListenSocket = new System.Net.Sockets.Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
//关联终结地
m_ListenSocket.Bind(this.Info.EndPoint);
//设置监听最大连接数
m_ListenSocket.Listen(m_ListenBackLog);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
//初始化套接字操作
SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
m_AcceptSAE = acceptEventArg;
//定义一个连接完成事件
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
if (!m_ListenSocket.AcceptAsync(acceptEventArg))
{
ProcessAccept(acceptEventArg);
}
return true;
}
catch (Exception e)
{
OnError(e);
return false;
}
}
开发者ID:babywzazy,项目名称:Server,代码行数:36,代码来源:TcpAsyncSocketListener.cs
示例17: CopyToNextSegment
public ArraySegment<byte> CopyToNextSegment(SocketAsyncEventArgs sourceEventArgs)
{
Byte[] array;
int offset;
int count = sourceEventArgs.BytesTransferred;
Locate(count, out array, out offset);
var data = new ArraySegment<byte>(array, offset, count);
if (sourceEventArgs.Buffer != null)
{
Buffer.BlockCopy(sourceEventArgs.Buffer, sourceEventArgs.Offset, array, offset, count);
}
else if (sourceEventArgs.BufferList != null)
{
int currentOffset = offset;
int copiedCount = 0;
foreach (var item in sourceEventArgs.BufferList)
{
int willcopyCount = count - copiedCount;
int copyingCount = willcopyCount > item.Count ? item.Count : willcopyCount;
Buffer.BlockCopy(item.Array, item.Offset, array, currentOffset, copyingCount);
copiedCount = copiedCount + copiedCount;
currentOffset = copiedCount + offset;
}
}
return data;
}
开发者ID:waynebaby,项目名称:Hyper-TCP-DotNet,代码行数:27,代码来源:ByteSegmentLocatorBase.cs
示例18: Start
/// <summary>
/// Starts to listen
/// </summary>
/// <param name="config">The server config.</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
m_ListenSocket = new Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
m_ListenSocket.Bind(this.Info.EndPoint);
m_ListenSocket.Listen(m_ListenBackLog);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
//
m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
if (!m_ListenSocket.AcceptAsync(acceptEventArg))
ProcessAccept(acceptEventArg);
return true;
}
catch (Exception e)
{
OnError(e);
return false;
}
}
开发者ID:kinghuc,项目名称:521266750_qq_com,代码行数:34,代码来源:TcpAsyncSocketListener.cs
示例19: OnConnection
public void OnConnection(object sender, SocketAsyncEventArgs e)
{
if (e.BytesTransferred > 0)
{
var packetData = new byte[e.BytesTransferred];
Buffer.BlockCopy(dataBuffer, 0, packetData, 0, e.BytesTransferred);
ProcessPacket(new Packet(packetData));
}
PacketLog.Write<Packet>(dataBuffer, e.BytesTransferred, client.RemoteEndPoint as IPEndPoint);
e.Completed -= OnConnection;
e.Completed += Process;
var sHello = new Packet(ServerMessage.SHello);
sHello.Write(9165, 32); // BuildNumber
sHello.Write(1, 32); // RealmId
sHello.Write(0, 32); // RealmGroupId
sHello.Write(0, 32);
sHello.Write(0, 64);
sHello.Write(0, 16);
sHello.Write(11, 5); // ConnectionType
sHello.Write(0xBDD06089, 32); // NetworkMessageCRC
sHello.Write(0, 32);
sHello.Write(0, 64);
sHello.Write(0, 32);
Send(sHello);
client.ReceiveAsync(e);
}
开发者ID:Captain-Ice,项目名称:Project-WildStar,代码行数:34,代码来源:RealmSession.cs
示例20: OSClient
public OSClient(IEFMagLinkRepository repository)
{
// First we set up our mutex and semaphore
mutex = new Mutex();
connected = false;
_repository = repository;
item = new SocketAsyncEventArgs();
_timerClient.Elapsed += new System.Timers.ElapsedEventHandler(_timerClient_Elapsed);
_timerClient.Interval = 10000;
_timerClient.Start();
_timerClientConnecTimer.Elapsed += new System.Timers.ElapsedEventHandler(_timerClientConnecTimer_Elapsed);
_timerClientConnecTimer.Interval = 15000;
_timerClientConnecTimer.Start();
numconnections = 0;
item.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted);
item.SetBuffer(new Byte[Convert.ToInt32(Settings._instance.BufferSize)], 0, Convert.ToInt32(Settings._instance.BufferSize));
socketpool = new OSAsyncEventStack(Convert.ToInt32(Settings._instance.NumConnect));
for (Int32 i = 0; i < Convert.ToInt32(Settings._instance.NumConnect); i++)
{
SocketAsyncEventArgs item1 = new SocketAsyncEventArgs();
item1.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted);
item1.SetBuffer(new Byte[Convert.ToInt32(Settings._instance.BufferSize)], 0, Convert.ToInt32(Settings._instance.BufferSize));
socketpool.Push(item1);
}
}
开发者ID:Cocotus,项目名称:High-Performance-.NET-Socket-Server-Using-Async-Winsock,代码行数:28,代码来源:OSClient.cs
注:本文中的System.Net.Sockets.SocketAsyncEventArgs类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论