本文整理汇总了C#中System.Net.Sockets.SocketAsyncEventArgs类的典型用法代码示例。如果您正苦于以下问题:C# SocketAsyncEventArgs类的具体用法?C# SocketAsyncEventArgs怎么用?C# SocketAsyncEventArgs使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SocketAsyncEventArgs类属于System.Net.Sockets命名空间,在下文中一共展示了SocketAsyncEventArgs类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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);
}
}
示例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);
}
}
示例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;
}
}
}
示例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);
}
示例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();
}
示例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);
}
示例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);
}
示例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;
}
示例10: SocketAsyncEventArgsProxy
public SocketAsyncEventArgsProxy(SocketAsyncEventArgs socketEventArgs, bool isRecyclable)
{
SocketEventArgs = socketEventArgs;
OrigOffset = socketEventArgs.Offset;
SocketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArgs_Completed);
IsRecyclable = isRecyclable;
}
示例11: SocketAsyncEventArgsDecorator
public SocketAsyncEventArgsDecorator(SocketAsyncEventArgs socketAsyncEventArgs)
{
if (socketAsyncEventArgs == null)
throw new ArgumentNullException("socketAsyncEventArgs");
this.socketAsyncEventArgs = socketAsyncEventArgs;
}
示例12: AllocNewAsyncArgs
SocketAsyncEventArgs AllocNewAsyncArgs()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += m_receiveCompleteHandler;
return args;
}
示例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;
}
示例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);
}
示例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();
}