本文整理汇总了C#中System.Net.Sockets.Socket.EndAccept方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.EndAccept方法的具体用法?C# Socket.EndAccept怎么用?C# Socket.EndAccept使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.EndAccept方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SocketPair
/// <summary>
/// Create 2 sockets connected to each other, for communication between threads.
/// </summary>
public static Socket[] SocketPair()
{
Socket Listener;
Socket[] Pair = new Socket[2];
// Start the listener side.
IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 0);
Listener = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Listener.Bind(endPoint);
Listener.Listen(1);
IAsyncResult ServerResult = Listener.BeginAccept(null, null);
// Connect the client to the server.
endPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)Listener.LocalEndPoint).Port);
Pair[0] = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult ClientResult = Pair[0].BeginConnect(endPoint, null, null);
// Get the server side socket.
Pair[1] = Listener.EndAccept(ServerResult);
Pair[0].EndConnect(ClientResult);
Listener.Close();
Pair[0].Blocking = false;
Pair[1].Blocking = false;
return Pair;
}
示例2: Server
public static void Server()
{
//创建一个新的Socket,这里我们使用最常用的基于TCP的Stream Socket(流式套接字)
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//将该socket绑定到主机上面的某个端口
socket.Bind(new IPEndPoint(IPAddress.Any, 8001));
//启动监听,并且设置一个最大的队列长度
socket.Listen(4);
//开始接受客户端连接请求
socket.BeginAccept(new AsyncCallback((ar) =>
{
//这就是客户端的Socket实例,我们后续可以将其保存起来
var client = socket.EndAccept(ar);
//给客户端发送一个欢迎消息
//client.Send(Encoding.Unicode.GetBytes("Hi there, I accept you request at " + DateTime.Now.ToString()));
//实现每隔两秒钟给服务器发一个消息
//这里我们使用了一个定时器
/*var timer = new System.Timers.Timer();
timer.Interval = 2000D;
timer.Enabled = true;
timer.Elapsed += (o, a) =>
{
//检测客户端Socket的状态
if (client.Connected)
{
try
{
client.Send(Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString()));
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
timer.Stop();
timer.Enabled = false;
Console.WriteLine("Client is disconnected, the timer is stop.");
}
};
timer.Start();*/
//接收客户端的消息(这个和在客户端实现的方式是一样的)
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
}), null);
}
示例3: EndAccept
// Подключение клиентов
private static void EndAccept(IAsyncResult ar)
{
try
{
Listener_Socket = (Socket)ar.AsyncState;
AddClient(Listener_Socket.EndAccept(ar));
Listener_Socket.BeginAccept(new AsyncCallback(EndAccept), Listener_Socket);
}
catch (Exception) { }
}
示例4: TestConnect28
//[Test]
public void TestConnect28()
{
for (int i = 0; i < 1000; ++i)
{
const AddressFamily family = AddressFamily.InterNetwork;
const SocketType socket = SocketType.Stream;
const ProtocolType protocol = ProtocolType.Tcp;
using (var client = new Socket(family, socket, protocol))
using (var server = new Socket(family, socket, protocol))
{
client.ReceiveTimeout = 10000;
server.ExclusiveAddressUse = true;
server.Bind(new IPEndPoint(IPAddress.Loopback, 60310));
bool isConnected = false;
server.Listen(1);
server.BeginAccept(ar =>
{
Console.WriteLine("BeginAccept handler");
var serverCon = server.EndAccept(ar);
Console.WriteLine("EndAccept called");
isConnected = true;
serverCon.Send(new byte[256]);
}, null);
try
{
client.Connect(server.LocalEndPoint);
Console.WriteLine("socket.Connected: {0} to {1}", client.Connected, client.RemoteEndPoint);
}
catch (Exception e)
{
throw new Exception(string.Format("Connect failed: {0}", e.Message), e);
}
client.Send(new byte[256]);
try
{
int length = client.Receive(new byte[256]);
Assert.AreEqual(length, 256);
}
catch (Exception e)
{
throw new Exception(string.Format("Receive #{0} failed (Connected: {1}): {2}",
i,
isConnected,
e.Message),
e);
}
}
}
}
示例5: ProcessClient
public SSPClient ProcessClient(SSPServer Server, Socket TcpServer, IAsyncResult result)
{
try
{
Socket AcceptSocket = TcpServer.EndAccept(result); //<- can throw a error
SSPClient client = Server.GetNewClient();
client.Handle = AcceptSocket;
if (AcceptSocket.AddressFamily == AddressFamily.InterNetworkV6)
client.RemoteIp = ((IPEndPoint)AcceptSocket.RemoteEndPoint).Address.ToString();
else
client.RemoteIp = AcceptSocket.RemoteEndPoint.ToString().Split(':')[0];
client.Server = Server;
client.Connection = new Network.Connection(client);
client.ClientId = Server.randomDecimal.NextDecimal();
client.serverHS = new ServerMaze(Server.serverProperties.Handshake_Maze_Size, Server.serverProperties.Handshake_MazeCount, Server.serverProperties.Handshake_StepSize);
client.serverHS.onFindKeyInDatabase += Server.serverHS_onFindKeyInDatabase;
SysLogger.Log("Accepted peer " + client.RemoteIp, SysLogType.Debug);
lock (Server.Clients)
{
while (Server.Clients.ContainsKey(client.ClientId))
client.ClientId = Server.randomDecimal.NextDecimal();
Server.Clients.Add(client.ClientId, client);
}
try
{
client.onBeforeConnect();
}
catch (Exception ex)
{
SysLogger.Log(ex.Message, SysLogType.Error);
client.onException(ex, ErrorType.UserLand);
}
client.Connection.StartReceiver();
return client;
}
catch (Exception ex)
{
SysLogger.Log(ex.Message, SysLogType.Error);
return null;
}
}
示例6: AsyncAccept
/// <summary>
/// Asyncs the connect.
/// </summary>
/// <param name="socket">The socket.</param>
/// <param name="accept">The accept.</param>
/// <param name="timeout">The timeout.</param>
private static Socket AsyncAccept(Socket socket, Func<Socket, AsyncCallback, object, IAsyncResult> accept, TimeSpan timeout)
{
var asyncResult = accept(socket, null, null);
if (asyncResult.AsyncWaitHandle.WaitOne(timeout))
{
try
{
return socket.EndAccept(asyncResult);
}
catch (SocketException)
{ }
catch (ObjectDisposedException)
{ }
}
return null;
}
示例7: Access
//服务端重载Access函数
public override void Access(string IP, int ServerPort, int Port, System.Action AccessAciton)
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//设置SOCKET允许多个SOCKET访问同一个本地IP地址和端口号
serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//本机预使用的IP和端口
IPEndPoint serverIP = new IPEndPoint(IPAddress.Any, ServerPort);
//绑定服务端设置的IP
serverSocket.Bind(serverIP);
//设置监听个数
serverSocket.Listen(1);
//异步接收连接请求
serverSocket.BeginAccept(ar =>
{
base.communicateSocket = serverSocket.EndAccept(ar);
AccessAciton();
}, null);
}
示例8: ConnectTest
public void ConnectTest()
{
ManualResetEvent trigger = new ManualResetEvent( false );
bool isConnected = false;
Socket socket = new Socket( AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp );
IPHostEntry dnsEntry = Dns.GetHostEntry( "localhost" );
// If this fails, consider changing the index. This could fail depending on the
// physical configuration of the host system.
IPEndPoint endPoint =
new IPEndPoint( dnsEntry.AddressList[1], 8089 );
socket.Bind( endPoint );
socket.Listen( 30 );
socket.BeginAccept( s =>
{
socket.EndAccept( s );
isConnected = true;
trigger.Set();
},
null );
Mock<ICoreSettings> settings = new Mock<ICoreSettings>();
NetworkFacadeFactory factory = new NetworkFacadeFactory(settings.Object);
factory.BeginConnect( "localhost",
8089,
( b, s ) =>
{
Assert.That( b, Is.True );
Assert.That( s, Is.Not.Null );
} );
Assert.That( trigger.WaitOne( 2000 ), Is.True );
Assert.That( isConnected, Is.True );
}
示例9: WaitForConnections
public void WaitForConnections()
{
Socket serverSocket = null;
try
{
serverSocket = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, _socketPort));
serverSocket.Listen(5);
while (true)
{
try
{
IAsyncResult res = serverSocket.BeginAccept(null, null);
Socket client = serverSocket.EndAccept(res);
var ct = new ClienteTcp(client, _endLine);
var t = new Thread(ct.TreatClient);
t.Name = "Socket treatClient";
t.Start();
}
catch (ThreadAbortException)
{
serverSocket.Close();
break;
}
catch (Exception ex)
{
EventLog.WriteEntry("low-level-sendkeys", string.Format("low-level-sendkeys error loop:\n{0}", ex), EventLogEntryType.Error);
Thread.Sleep(5000);
}
}
}
catch (ThreadAbortException)
{
if (serverSocket != null) serverSocket.Close();
}
catch (Exception ex)
{
EventLog.WriteEntry("low-level-sendkeys", string.Format("low-level-sendkeys error:\n{0}", ex), EventLogEntryType.Error);
throw;
}
}
示例10: Main
public static void Main (string [] args)
{
IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10000);
Socket accept = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Socket client = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Socket listener = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
listener.Bind (ep);
listener.Listen (8);
IAsyncResult listenResult = listener.BeginAccept (accept,
0, null, null);
client.Connect (ep);
Assert.IsFalse (accept.Connected, "#1");
Socket connected = listener.EndAccept (listenResult);
Assert.IsTrue (accept.Connected, "#2");
Assert.AreSame (connected, accept, "#3");
}
示例11: HttpClientContextTest
public HttpClientContextTest()
{
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.Bind(new IPEndPoint(IPAddress.Any, 14862));
_listenSocket.Listen(0);
IAsyncResult res = _listenSocket.BeginAccept(null, null);
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_client.Connect("localhost", 14862);
_remoteSocket = _listenSocket.EndAccept(res);
_disconnectEvent.Reset();
_event.Reset();
_counter = 0;
var requestParserFactory = new RequestParserFactory();
_factory = new HttpContextFactory(NullLogWriter.Instance, 8192, requestParserFactory);
_factory.RequestReceived += OnRequest;
_context = _factory.CreateContext(_client);
_context.Disconnected += OnDisconnect;
//_context = new HttpClientContextImp(false, new IPEndPoint(IPAddress.Loopback, 21111), OnRequest, OnDisconnect, _client.GetStream(), ConsoleLogWriter.Instance);
_request = null;
_disconnected = false;
}
示例12: OnConnectRequest
//当有客户端连接时的处理
public void OnConnectRequest(IAsyncResult ar)
{
//初始化一个SOCKET,用于其它客户端的连接
server1 = (Socket)ar.AsyncState;
Client = server1.EndAccept(ar);
//将要发送给连接上来的客户端的提示字符串
DateTimeOffset now = DateTimeOffset.Now;
// string strDateLine = "Welcome";
// Byte[] byteDateLine = System.Text.Encoding.UTF8.GetBytes(strDateLine);
//将提示信息发送给客户端,并在服务端显示连接信息。
remote = Client.RemoteEndPoint;
showClientMsg(now.ToString("G") + Client.RemoteEndPoint.ToString() + " Connected " + "\r\n");
// Client.Send(byteDateLine, byteDateLine.Length, 0);
userListOperate(Client.RemoteEndPoint.ToString());
//把连接成功的客户端的SOCKET实例放入哈希表
_sessionTable.Add(Client.RemoteEndPoint, null);
//等待新的客户端连接
server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1);
byte[] RevBuffer = new byte[1024];
while (true)
{
int recv = Client.Receive(RevBuffer);
string stringdata = Encoding.UTF8.GetString(RevBuffer, 0, recv);
string ip = Client.RemoteEndPoint.ToString();
//获取客户端的IP和端口
if (stringdata == "STOP")
{
//当客户端终止连接时
showClientMsg(now.ToString("G") + "-->" + ip + " Disconnected " + "\r\n");
_sessionTable.Remove(Client.RemoteEndPoint);
break;
}
//显示客户端发送过来的信息
showClientMsg(now.ToString("G") + "--> " + ip + " " + stringdata + "\r\n");
string SeqNo = stringdata.Substring(0, 6);
string BcrNo = stringdata.Substring(6, 1);
string Flag = stringdata.Substring(7, 1);
bool Result = HandleDatafromErp(SeqNo, BcrNo, Flag);
string Msg = string.Format("{0}{1}", SeqNo, Result ? "1" : "0");
Byte[] sendData = Encoding.UTF8.GetBytes(Msg);
Client.Send(sendData, sendData.Length, 0);
}
}
示例13: Listen
public IAsyncResult Listen()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(IPAddress.Loopback, 5050));
_socket.Listen(1);
return _socket.BeginAccept(delegate(IAsyncResult asyncResult)
{
try
{
var client = _socket.EndAccept(asyncResult);
using (var networkStream = new NetworkStream(client))
using (var streamReader = new StreamReader(networkStream))
{
Assert.That(streamReader.ReadToEnd(), Is.EqualTo(_expectedText));
}
}
catch (ObjectDisposedException)
{
Error = true;
}
}, null);
}
示例14: ProcessConnection
void ProcessConnection(Socket listener, IAsyncResult ar)
{
Socket ns = listener.EndAccept (ar);
ns.NoDelay = true;
SslStream ssl = new SslStream (new NetworkStream (ns, true));
ssl.BeginAuthenticateAsServer (cert, (IAsyncResult ar2) => {
try {
ssl.EndAuthenticateAsServer (ar2);
Protocol p = new Protocol ();
p.OnMessage += (incoming) => {
var hdr = incoming.Header;
// TODO timeout handling
if (hdr ["type"].AsString(null) != "request") {
Logger.LogError ("received non-request");
incoming.Discard ();
return;
}
if (!hdr.ContainsKey ("request_id")) {
Logger.LogError ("Received request with no request_id");
incoming.Discard ();
return;
}
var id = hdr ["request_id"];
reqh (incoming, (reply) => {
reply.Header ["type"] = "reply";
reply.Header ["request_id"] = id;
p.SendMessage (reply);
});
};
p.OnClose += (error) => {
Logger.LogInfo ("scamp connection closed: {0}", error);
};
p.Start (ssl);
} catch (Exception ex) {
Logger.LogError ("connection server authenticate: {0}", ex);
}
}, null);
}
示例15: AcceptAsync
private static Task<Socket> AcceptAsync(Socket socket)
{
return Task.Factory.FromAsync((cb, state) => socket.BeginAccept(cb, state), ar => socket.EndAccept(ar), null);
}