本文整理汇总了C#中System.Net.Sockets.Socket.AcceptAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.AcceptAsync方法的具体用法?C# Socket.AcceptAsync怎么用?C# Socket.AcceptAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.AcceptAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
}
示例2: Listen
internal void Listen(String ipAddress, Int32 portNo)
{
try
{
if (_listenSocket != null)
throw new AegisException(AegisResult.AcceptorIsRunning, "Acceptor is already running.");
if (ipAddress.Length == 0)
_listenEndPoint = new IPEndPoint(IPAddress.Any, portNo);
else
_listenEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), portNo);
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.Bind(_listenEndPoint);
_listenSocket.Listen(100);
Logger.Write(LogType.Info, 1, "Listening on {0}, {1}", _listenEndPoint.Address, _listenEndPoint.Port);
_listenSocket.AcceptAsync(_eventAccept);
}
catch (AegisException)
{
throw;
}
catch (Exception e)
{
throw new AegisException(AegisResult.NetworkError, e, e.Message);
}
}
示例3: StartListening
public void StartListening(int port)
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, port);
try
{
listener.Bind(ipEndPoint);
listener.Listen(5);
while(true)
{
allDone.Reset();
listener.AcceptAsync(new SocketAsyncEventArgs()
{
});
allDone.WaitOne();
}
}
catch (Exception ex)
{
}
}
示例4: EndPointListener
public EndPointListener(
IPAddress address,
int port,
bool secure,
string certFolderPath,
X509Certificate2 defaultCert
)
{
if (secure) {
_secure = secure;
_cert = getCertificate (port, certFolderPath, defaultCert);
if (_cert == null)
throw new ArgumentException ("Server certificate not found.");
}
_endpoint = new IPEndPoint (address, port);
_socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind (_endpoint);
_socket.Listen (500);
var args = new SocketAsyncEventArgs ();
args.UserToken = this;
args.Completed += onAccept;
_socket.AcceptAsync (args);
_prefixes = new Dictionary<ListenerPrefix, HttpListener> ();
_unregistered = new Dictionary<HttpConnection, HttpConnection> ();
}
示例5: Initialize
private void Initialize(IPEndPoint endpoint, Action<TcpStreamChannel> onClientAccepted)
{
if (endpoint == null)
{
throw new ArgumentNullException("endpoint");
}
if (onClientAccepted == null)
{
throw new ArgumentNullException("onClientConnected");
}
_onClientAcceptedAction = onClientAccepted;
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
_listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
_listenSocket.Bind(endpoint);
_listenSocket.Listen(10);
_acceptEventArg = new SocketAsyncEventArgs();
_acceptEventArg.Completed += OnAcceptNewClient;
if (!_listenSocket.AcceptAsync(_acceptEventArg))
{
OnAcceptNewClient(null, _acceptEventArg);
}
}
示例6: Listen
private void Listen(IPEndPoint localEndpoint)
{
_logger.Trace("Listen (sync) using local endpoint {0}", localEndpoint);
// create a socket
_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// bind and listen
try
{
_listener.Bind(localEndpoint);
_listener.Listen(1);
// accept the next connection
bool completesAsynchronously = _listener.AcceptAsync(_socketOperation);
if (!completesAsynchronously)
{
SocketAsyncEventArgs_Completed(_socketOperation.AcceptSocket, _socketOperation);
}
}
catch (Exception ex)
{
// raise error event
var handlers = Error;
if (handlers != null)
{
var args = new NetworkErrorEventArgs("The listen operation failed: " + ex.ToString(), null, ex);
handlers(this, args);
}
}
}
示例7: 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;
}
}
示例8: AcceptAsyncShouldUseAcceptSocketFromEventArgs
public void AcceptAsyncShouldUseAcceptSocketFromEventArgs()
{
var readyEvent = new ManualResetEvent(false);
var mainEvent = new ManualResetEvent(false);
var listenSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var serverSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket acceptedSocket = null;
Exception ex = null;
ThreadPool.QueueUserWorkItem(_ =>
{
SocketAsyncEventArgs asyncEventArgs;
try {
listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listenSocket.Listen(1);
asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
asyncEventArgs.Completed += (s, e) =>
{
acceptedSocket = e.AcceptSocket;
mainEvent.Set();
};
} catch (Exception e) {
ex = e;
return;
} finally {
readyEvent.Set();
}
try {
if (listenSocket.AcceptAsync(asyncEventArgs))
return;
acceptedSocket = asyncEventArgs.AcceptSocket;
mainEvent.Set();
} catch (Exception e) {
ex = e;
}
});
Assert.IsTrue(readyEvent.WaitOne(1500));
if (ex != null)
throw ex;
var clientSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(listenSocket.LocalEndPoint);
clientSocket.NoDelay = true;
Assert.IsTrue(mainEvent.WaitOne(1500));
Assert.AreEqual(serverSocket, acceptedSocket, "x");
mainEvent.Reset();
if (acceptedSocket != null)
acceptedSocket.Close();
listenSocket.Close();
readyEvent.Close();
mainEvent.Close();
}
示例9: acceptAsync
void acceptAsync(Socket socket, SocketAsyncEventArgs e)
{
e.AcceptSocket = null;
if (socket.AcceptAsync(e) == false)
{
acceptAsyncEvent_Completed(socket, e);
}
}
示例10: Accept
public void Accept(Socket ListenSock)
{
if (false == ListenSock.AcceptAsync(FAcceptEventArg))
{
OnCompleted(ListenSock, FAcceptEventArg);
}
}
示例11: AcceptSocketAsync
public static async Task AcceptSocketAsync(Socket server, Func<Socket, NetworkStream, StreamReader, StreamWriter, Task> funcAsync)
{
using (Socket s = await server.AcceptAsync().ConfigureAwait(false))
using (var stream = new NetworkStream(s, ownsSocket: false))
using (var reader = new StreamReader(stream, Encoding.ASCII))
using (var writer = new StreamWriter(stream, Encoding.ASCII))
{
await funcAsync(s, stream, reader, writer).ConfigureAwait(false);
}
}
示例12: ServerMock
/// <summary>
/// Start and listen ongoing TCP connections on the localhost on the given port
/// </summary>
/// <param name="port">port number of the connection. Use 0 for any availble port.</param>
public ServerMock(int port)
{
var endpoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
_socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(endpoint);
ListenEndPoint = _socket.LocalEndPoint as IPEndPoint;
_socket.Listen((int)SocketOptionName.MaxConnections);
var acceptEventArgs = GetAcceptEventArgs();
if (!_socket.AcceptAsync(acceptEventArgs))
throw new Exception("Unable to listen on " + ListenEndPoint);
_acceptedSockets = new List<Socket>();
ResponseHeader = new byte[MemcacheResponseHeader.Size];
}
示例13: start
private void start()
{
m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9001);
m_ServerSocket.Bind(ipep);
m_ServerSocket.Listen(20);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
m_ServerSocket.AcceptAsync(args);
while (true)
{
}
}
示例14: AcceptAsync
public AwaitIo AcceptAsync(Socket listener, bool post_read_buffers = false)
{
if (post_read_buffers)
{
var ds = _data.GetSegmentToRead();
int pos = ds.Count, bts = ds.Size - pos;
SetBuffer(ds.Buffer, ds.Offset + pos, bts);
}
// see Recv() comments on SuppressFlow.
var async = false;
var aFC = ExecutionContext.SuppressFlow();
try { async = listener.AcceptAsync(this); } finally { aFC.Undo(); }
return CheckCompleted(async);
}
示例15: Initialize
public override void Initialize()
{
if (_socket != null) return;
_socket = new Socket(_ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.ExclusiveAddressUse = true;
_socket.Bind(new IPEndPoint(_ipv6 ? IPAddress.IPv6Any : IPAddress.Any, _port));
_socket.Listen(100);
var args = new SocketAsyncEventArgs();
args.Completed += AcceptAsyncCompleted;
_socket.AcceptAsync(args);
}