本文整理汇总了C#中System.Net.Sockets.SocketAsyncEventArgs.SetBuffer方法的典型用法代码示例。如果您正苦于以下问题:C# SocketAsyncEventArgs.SetBuffer方法的具体用法?C# SocketAsyncEventArgs.SetBuffer怎么用?C# SocketAsyncEventArgs.SetBuffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.SocketAsyncEventArgs
的用法示例。
在下文中一共展示了SocketAsyncEventArgs.SetBuffer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SetBuffer
/// <summary>
/// Sets the buffer for a <see cref="SocketAsyncEventArgs"/> object.
/// </summary>
/// <param name="eventArgs">The SAEA whose buffer will be set</param>
/// <returns>True if the bucket was set.</returns>
public virtual bool SetBuffer(SocketAsyncEventArgs eventArgs)
{
lock (_freeIndexPool)
{
EnsureBufferAllocated();
var isBufferSet = true;
if (_freeIndexPool.Count > 0)
{
eventArgs.SetBuffer(_buffer, _freeIndexPool.Pop(), _bufferSize);
}
else
{
if ((_numberOfBytes - _bufferSize) < _currentIndex)
{
isBufferSet = false;
}
else
{
eventArgs.SetBuffer(_buffer, _currentIndex, _bufferSize);
_currentIndex += _bufferSize;
}
}
return isBufferSet;
}
}
示例2: SetBuffer
public void SetBuffer(SocketAsyncEventArgs args)
{
if (_availableBuffers.Count > 0)
{
int index = _availableBuffers.Pop();
byte[] buffer;
lock (_bufferLocker)
{
buffer = _buffers[index];
}
args.SetBuffer(buffer, 0, buffer.Length);
}
else
{
byte[] buffer = new byte[_bufferSize];
lock (_bufferLocker)
{
_buffers.Add(buffer);
}
args.SetBuffer(buffer, 0, buffer.Length);
}
}
示例3: SetBuffer
public void SetBuffer(SocketAsyncEventArgs args)
{
if (m_FreeIndex.Count > 0)
{
args.SetBuffer(m_BufferBlock, m_FreeIndex.Pop(), m_BufferSize);
}
else
{
args.SetBuffer(m_BufferBlock, m_CurrentIndex, m_BufferSize);
m_CurrentIndex += m_BufferSize;
}
}
示例4: PartitionBuffer
///<summary>Partitions a section of the pool for the provided SocketAsyncEventArgs object.</summary>
/// <returns>True if the buffer was successfully partitioned and allocated. False otherwise.</returns>
public bool PartitionBuffer(SocketAsyncEventArgs args)
{
if (free_index_pool.Count > 0) {
args.SetBuffer(buffer, free_index_pool.Pop(), chunk_size);
} else {
if ((total_managed_size - chunk_size) < current_index)
return false;
args.SetBuffer(buffer, current_index, chunk_size);
current_index += chunk_size;
}
return true;
}
示例5: SetBuffer_ByteArray
public void SetBuffer_ByteArray ()
{
SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
byte [] buffer = new byte [0];
saea.SetBuffer (buffer, 0, 0);
Assert.AreEqual (0, saea.Buffer.Length, "0");
Assert.AreSame (saea.Buffer, buffer, "same");
saea.SetBuffer (null, 0, 0);
Assert.IsNull (saea.Buffer, "null");
}
示例6: SendTimeRequest
partial void SendTimeRequest()
{
try
{
byte[] buffer = new byte[48];
buffer[0] = 0x1B;
DnsEndPoint _endPoint = new DnsEndPoint(_ServerAddress, 123, AddressFamily.InterNetwork);
Socket socket = null;
var socketArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
socketArgs.Completed += Socket_Completed_SendAgain;
//TFW - For some reason 'ConnectAsync' reports an error
//desktop .Net 4, but 'Connect' works fine. On WP
//only ConnectAsync is available, and it appears to work.
#if USE_CONNECTASYNC
socketArgs.SetBuffer(buffer, 0, buffer.Length);
if (!socket.ConnectAsync(socketArgs))
Socket_Completed_SendAgain(socket, socketArgs);
#else
socket.Connect(socketArgs.RemoteEndPoint);
socketArgs.SetBuffer(buffer, 0, buffer.Length);
if (!socket.SendAsync(socketArgs))
Socket_Completed_SendAgain(socket, socketArgs);
#endif
}
catch
{
socketArgs.Completed -= this.Socket_Completed_SendAgain;
throw;
}
}
catch
{
socket?.Dispose();
throw;
}
}
catch (SocketException se)
{
OnErrorOccurred(new NtpNetworkException(se.Message, (int)se.SocketErrorCode, se));
}
catch (Exception ex)
{
OnErrorOccurred(new NtpNetworkException(ex.Message, -1, ex));
}
}
示例7: SendData
/// <summary>
/// Format data for sending to client and assign an event handler for the Completed event
/// </summary>
/// <param name="ResponseCode"></param>
/// <param name="Data"></param>
internal void SendData(ServerResponseCode ResponseCode, string Data)
{
// Get a new SocketAsyncEventArgs object:
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
// Create response and buffer it:
byte[] buffer = ServerResponse(ResponseCode, Data);
e.SetBuffer(buffer, 0, buffer.Length);
// Send a reference to this object for use in next callback:
e.UserToken = this;
// Store our last response:
LastServerResponse = ResponseCode;
// Assign delegate to handle the Completed event
switch (ResponseCode)
{
case ServerResponseCode.None:
throw new ArgumentException();
case ServerResponseCode.DISCON:
case ServerResponseCode.SERVICE_NOT_AVAILABLE:
e.Completed += this.rejectConnectionDelegate;
break;
default:
e.Completed += this.DataSentDelegate;
break;
}
// Blast that data down the wire yo:
m_WorkerSocket.SendAsync(e);
}
示例8: SendMessage
public IObservable<Unit> SendMessage(Socket connectedSocket, SocketAsyncEventArgs socketEventArgs, IScheduler scheduler, string message)
{
if (connectedSocket == null)
throw new ArgumentNullException("connectedSocket");
if (socketEventArgs == null)
throw new ArgumentNullException("socketEventArgs");
return Observable.Create<Unit>(observer =>
{
var disposable = new CompositeDisposable();
var buffer = Encoding.UTF8.GetBytes(message);
var disposableCompletedSubscription = socketEventArgs.CompletedObservable().ObserveOn(scheduler).Subscribe(_ =>
{
SendNotificationToObserver(observer, socketEventArgs);
});
var disposableActions = scheduler.Schedule(() =>
{
socketEventArgs.SetBuffer(buffer, 0, buffer.Length);
if (!connectedSocket.SendAsync(socketEventArgs))
{
SendNotificationToObserver(observer, socketEventArgs);
}
});
disposable.Add(disposableCompletedSubscription);
disposable.Add(disposableActions);
return disposable;
});
}
示例9: Pop
// Removes a SocketAsyncEventArgs instance from the pool.
// returns SocketAsyncEventArgs removed from the pool.
public SocketAsyncEventArgs Pop()
{
lock (this.pool)
{
SocketAsyncEventArgs args = null;
if (pool.Count > 0)
{
args = this.pool.Pop();
}
else
{
args = new SocketAsyncEventArgs();
byte[] buffer = new byte[1024];
args.SetBuffer(buffer, 0, buffer.Length);
SockState recState = new SockState(args, buffer.Length, null);
recState.IsCached = false;
recState.ID = Interlocked.Decrement(ref SockStateID);
args.UserToken = recState;
recState.BufferBlockOffset = 0;
recState.BufferBlockLength = 1024;
}
return args;
}
}
示例10: SendBytes
public void SendBytes(byte[] data)
{
SocketAsyncEventArgs enew = new SocketAsyncEventArgs();
enew.Completed += SockAsyncEventArgs_Completed;
enew.SetBuffer(data, 0, data.Length);
SendAsync(enew);
}
示例11: Receive_Completed
private void Receive_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = (Socket)sender;
Console.WriteLine("Receiving data");
if (ClientSocket.Connected && e.BytesTransferred > 0)
{
byte[] bytesFrom = e.Buffer; // 데이터 수신
String dataFromLobby = System.Text.Encoding.UTF8.GetString(bytesFrom);
gameRoomInfo gameroominfo = JsonConvert.DeserializeObject<gameRoomInfo>(dataFromLobby);
if (gameroominfo != null)
{
GameRoom gameRoom = new GameRoom(gameroominfo);
Console.WriteLine("Game Created");
//string Test = sData.Replace("\0", "").Trim();
for (int i = 0; i < szData.Length; i++)
{
szData[i] = 0;
}
e.SetBuffer(szData, 0, 1024);
ClientSocket.ReceiveAsync(e);
}
}
else
{
Console.WriteLine("Lobby Server Disconnected");
ClientSocket.Disconnect(false);
ClientSocket.Dispose();
}
}
示例12: Start
/// <summary>
/// Starts to listen
/// </summary>
/// <param name="config">The server config.</param>
/// <returns></returns>
public override bool Start(IServerConfig config)
{
try
{
m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
m_ListenSocket.Bind(this.EndPoint);
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
byte[] optionInValue = { Convert.ToByte(false) };
byte[] optionOutValue = new byte[4];
m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
var eventArgs = new SocketAsyncEventArgs();
eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int receiveBufferSize = config.ReceiveBufferSize <= 0 ? 2048 : config.ReceiveBufferSize;
var buffer = new byte[receiveBufferSize];
eventArgs.SetBuffer(buffer, 0, buffer.Length);
m_ListenSocket.ReceiveFromAsync(eventArgs);
return true;
}
catch (Exception e)
{
OnError(e);
return false;
}
}
示例13: Send
/// <summary>Sends data to remote host.</summary>
/// <param name="buffer">Data to send.</param>
/// <param name="offset">Offset.</param>
/// <param name="count">Amount of bytes to send.</param>
public void Send(byte[] buffer, int offset, int count)
{
var evnt = new SocketAsyncEventArgs();
evnt.Completed += OnSendComplete;
evnt.SetBuffer(buffer, offset, count);
_socket.SendAsync(evnt);
}
示例14: 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();
}
示例15: 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);
}
}