本文整理汇总了C#中System.Net.Sockets.TcpListener.EndAcceptTcpClient方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.EndAcceptTcpClient方法的具体用法?C# TcpListener.EndAcceptTcpClient怎么用?C# TcpListener.EndAcceptTcpClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.TcpListener
的用法示例。
在下文中一共展示了TcpListener.EndAcceptTcpClient方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main(string[] args)
{
Action<object> cw = Console.WriteLine;
cw("* any");
cw(IPAddress.Any);
cw(IPAddress.IPv6Any);
cw("* loopback");
cw(IPAddress.Loopback);
cw(IPAddress.IPv6Loopback);
cw("* none");
cw(IPAddress.None);
cw(IPAddress.IPv6None);
cw("* bc4"); //trivia: there is no bc6, only multicast
cw(IPAddress.Broadcast);
TcpListener l = new TcpListener(IPAddress.Any, 7896);
l.Start();
l.BeginAcceptTcpClient(ar => {
var c = l.EndAcceptTcpClient(ar);
l.Stop();
//var s = new StreamWriter(c.GetStream());
//s.WriteLine("test writer : needed");
//s.Flush();
var bs = System.Text.Encoding.UTF8.GetBytes("test direct : not needed");
c.GetStream().Write(bs, 0, bs.Length);
c.Close();
}, l);
//start client
var q = new TcpClient("localhost", 7896);
var qs = new StreamReader(q.GetStream());
Console.WriteLine(qs.ReadLine());
// l.Stop();
}
示例2: ThreadProc
private void ThreadProc()
{
TcpListener listner = null;
try
{
listner = new TcpListener(IPAddress.Any, _connectionString.Port);
listner.Start(1);
Thread clientThread = null;
do
{
try
{
//_tcpClientConnected.Reset();
IAsyncResult aResult = listner.BeginAcceptTcpClient(null, null);
int eventIndex = WaitHandle.WaitAny(new[] { _exit, aResult.AsyncWaitHandle });
if (eventIndex == 0) break;
//using (TcpClient client = listner.EndAcceptTcpClient(aResult))
//{
// aResult.AsyncWaitHandle.Close();
// ReadInLoop(client);
//}
TcpClient client = listner.EndAcceptTcpClient(aResult);
aResult.AsyncWaitHandle.Close();
if (_tcpClientConnected != null)
_tcpClientConnected.Set();
else
_tcpClientConnected = new AutoResetEvent(false);
if (clientThread != null && clientThread.ThreadState == ThreadState.Running)
clientThread.Join();
clientThread = new Thread(ReadInLoop) { IsBackground = true };
clientThread.Start(client);
//_client = listner.EndAcceptTcpClient(aResult);
//aResult.AsyncWaitHandle.Close();
//listner.Stop();
//_client.Client.ReceiveTimeout = ReceiveTimeout;
//ReadInLoop();
}
catch (Exception ex)
{
_log.WriteError(string.Format("TcpExternalSystemServer: {0}", ex));
Thread.Sleep(5000);
}
} while (!_exit.WaitOne(0));
listner.Stop();
}
catch (Exception ex)
{
_log.WriteError(string.Format("TcpExternalSystemServer.ThreadProc:\n{0}",ex));
}
finally
{
listner = null;
}
}
示例3: Run
/// <summary>
/// Server's main loop implementation.
/// </summary>
/// <param name="log"> The Logger instance to be used.</param>
public void Run(Logger log)
{
try
{
_srv = new TcpListener(IPAddress.Loopback, _portNumber);
_srv.Start();
log.Start();
AsyncCallback callback = null;
callback = delegate(IAsyncResult iar)
{
TcpClient socket = _srv.EndAcceptTcpClient(iar);
log.LogMessage("Listener - Waiting for connection requests.");
_srv.BeginAcceptTcpClient(callback, _srv);
// Process the previous request
try
{
socket.LingerState = new LingerOption(true, LingerTime);
log.LogMessage(String.Format("Listener - Connection established with {0}.",
socket.Client.RemoteEndPoint));
log.LogMessage(String.Format("Listener - Connection is going to last {0} seconds",
LingerTime));
// Instantiating protocol handler and associate it to the current TCP connection
Handler protocolHandler = new Handler(socket.GetStream(), log);
// Synchronously process requests made through de current TCP connection
protocolHandler.Run();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
ShowInfo(Store.Instance);
};
log.LogMessage("Listener - Waiting for connection requests.");
_srv.BeginAcceptTcpClient(callback, _srv);
}
catch (Exception)
{
log.LogMessage("Listener - Ending.");
log.Stop();
_srv.Stop();
}
}
示例4: ClientConnection
internal ClientConnection(ServerView father, TcpClient textTcp, String password, ArrayList name)
{
this._father = father;
this._textTcp = textTcp;
ChallengeMessage auth = new ChallengeMessage();
auth.salt = new Random().Next().ToString();
auth.sendMe(textTcp.GetStream()); //mando il sale
ResponseChallengeMessage respo = ResponseChallengeMessage.recvMe(textTcp.GetStream());
if (name.Contains(respo.username))
{
//connessione fallita
ConfigurationMessage fail = new ConfigurationMessage("Nome utente già utilizzato");
fail.sendMe(textTcp.GetStream());
throw new ClientConnectionFail("Un client ha fornito un nome utente già utilizzato");
}
this._username = respo.username;
if (Pds2Util.createPswMD5(password, auth.salt).Equals(respo.pswMd5))
{
//creo le connessioni per i socket clipboard e video
IPAddress localadd = ((IPEndPoint)textTcp.Client.LocalEndPoint).Address;
TcpListener lvideo = new TcpListener(localadd, 0);
lvideo.Start();
IAsyncResult videores = lvideo.BeginAcceptTcpClient(null, null);
TcpListener lclip = new TcpListener(localadd, 0);
lclip.Start();
IAsyncResult clipres = lclip.BeginAcceptTcpClient(null, null);
int porta_video = ((IPEndPoint)lvideo.LocalEndpoint).Port;
int clip_video = ((IPEndPoint)lclip.LocalEndpoint).Port;
new ConfigurationMessage(porta_video, clip_video, "Benvenuto")
.sendMe(textTcp.GetStream());
_clipTcp = lclip.EndAcceptTcpClient(clipres);
_videoTcp = lvideo.EndAcceptTcpClient(videores);
//now the client is connected
_textReceiver = new Thread(_receiveText);
_textReceiver.IsBackground = true;
_textReceiver.Start();
_clipReceiver = new Thread(_receiveClipboard);
_clipReceiver.IsBackground = true;
_clipReceiver.Start();
}
else
{
//connessione fallita
ConfigurationMessage fail = new ConfigurationMessage("password sbagliata");
fail.sendMe(textTcp.GetStream());
throw new ClientConnectionFail("Un client ha fornito una password sbagliata");
}
}
示例5: HandleRecieve
/// <summary>
/// Handle an incoming connection
/// </summary>
private void HandleRecieve(IAsyncResult result, TcpListener listener)
{
// Print debug message waiting for data
AppendDebugListMessage("Waiting for data.");
// Interrupt this process once stop listenening is true
if (StopListening) return;
// Accept connection
using (TcpClient client = listener.EndAcceptTcpClient(result))
{
client.NoDelay = true;
// Get the data stream ftom the tcp client
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
// read data from sender
string data = reader.ReadLine();
// write the line to the console
Console.WriteLine(data);
// Send the received data back to the sender
// in Order to make sure we recieved the
// right amount and correct data.
writer.WriteLine(data);
// Send our Categories, Families and Types to Grasshopper
writer.WriteLine(FamiliesToRespond);
// if there is some useful data
if (data != null && data.Length > 5)
{
// Set the debugger message
AppendDebugListMessage("Received " + data.Length + " Bytes.");
// Deserialize the received data string
Grevit.Types.ComponentCollection cc = StringToComponents(data);
// If anything useful has been deserialized
if (cc != null && cc.Items.Count > 0)
{
// Add Component collection to the client static component collection
AddComponents(cc);
// print another debug message about the component received
AppendDebugListMessage("Translated " + cc.Items.Count.ToString() + " components.");
// set stop listening switch
StopListening = true;
}
}
}
}
}
}
// If stop listening is set stop all listening processes
if (StopListening)
{
// Stop the listener
listener.Server.Close();
listener.Stop();
// Wait until processes are stopped
Thread.Sleep(2000);
// close the dialog automatically
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
示例6: LogonUserTCPListen
private static WindowsIdentity LogonUserTCPListen(string userName, string domain, string password)
{
// need a full duplex stream - loopback is easiest way to get that
TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 0);
tcpListener.Start();
ManualResetEvent done = new ManualResetEvent(false);
WindowsIdentity id = null;
tcpListener.BeginAcceptTcpClient(delegate(IAsyncResult asyncResult)
{
try
{
using (NegotiateStream serverSide = new NegotiateStream(
tcpListener.EndAcceptTcpClient(asyncResult).GetStream()))
{
serverSide.AuthenticateAsServer(CredentialCache.DefaultNetworkCredentials,
ProtectionLevel.None, TokenImpersonationLevel.Impersonation);
id = (WindowsIdentity)serverSide.RemoteIdentity;
}
}
catch
{ id = null; }
finally
{ done.Set(); }
}, null);
using (NegotiateStream clientSide = new NegotiateStream(new TcpClient("localhost",
((IPEndPoint)tcpListener.LocalEndpoint).Port).GetStream()))
{
try
{
clientSide.AuthenticateAsClient(new NetworkCredential(userName, password, domain),
"", ProtectionLevel.None, TokenImpersonationLevel.Impersonation);
}
catch
{ id = null; }//When the authentication fails it throws an exception
}
tcpListener.Stop();
done.WaitOne();//Wait until we really have the id populated to continue
return id;
}
示例7: StartListening
private void StartListening(TcpListener server)
{
if (_shouldStop)
{
return;
}
server.BeginAcceptTcpClient(new AsyncCallback(delegate(IAsyncResult result)
{
TcpClient client = null;
try
{
client = server.EndAcceptTcpClient(result);
}
catch (Exception e)
{
LogManger.Error(e, this.GetType());
}
if (client != null)
{
ThreadPool.QueueUserWorkItem(ClientReceiveMessage, client);
}
StartListening(server);
}), server);
}
示例8: TestAsyncBasic
public void TestAsyncBasic()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start(5);
var ep = (IPEndPoint)listener.LocalEndpoint;
Console.WriteLine("Server> waiting for accept");
listener.BeginAcceptTcpClient((IAsyncResult ar) =>
{
var client = listener.EndAcceptTcpClient(ar);
var sslStream = new SslStream(client.GetStream(), false);
Console.WriteLine("Server> authenticate");
sslStream.BeginAuthenticateAsServer(_ctx.ServerCertificate, async (ar2) =>
{
sslStream.EndAuthenticateAsServer(ar2);
Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);
var buf = new byte[256];
await sslStream.ReadAsync(buf, 0, buf.Length);
Assert.AreEqual(clientMessage.ToString(), buf.ToString());
await sslStream.WriteAsync(serverMessage, 0, serverMessage.Length);
sslStream.Close();
client.Close();
Console.WriteLine("Server> done");
}, null);
}, null);
var evtDone = new AutoResetEvent(false);
var tcp = new TcpClient(AddressFamily.InterNetwork);
tcp.BeginConnect(ep.Address.ToString(), ep.Port, (IAsyncResult ar) =>
{
tcp.EndConnect(ar);
var sslStream = new SslStream(tcp.GetStream());
Console.WriteLine("Client> authenticate");
sslStream.BeginAuthenticateAsClient("localhost", async (ar2) =>
{
sslStream.EndAuthenticateAsClient(ar2);
Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);
await sslStream.WriteAsync(clientMessage, 0, clientMessage.Length);
var buf = new byte[256];
await sslStream.ReadAsync(buf, 0, buf.Length);
Assert.AreEqual(serverMessage.ToString(), buf.ToString());
sslStream.Close();
tcp.Close();
Console.WriteLine("Client> done");
evtDone.Set();
}, null);
}, null);
evtDone.WaitOne();
}
示例9: Server
static IEnumerator<Int32> Server(AsyncEnumerator ae, ServerState server)
{
var sleeper = new CountdownTimer();
var settings = server.settings;
var ipe = new IPEndPoint(IPAddress.Parse(settings.addressforward), settings.portforward);
var serverSock = new TcpListener(IPAddress.Parse(settings.addresslisten), settings.portlisten);
serverSock.Start(20);
Console.WriteLine("Server started");
Console.WriteLine("Listening on {0}:{1}", settings.addresslisten, settings.portlisten);
Console.WriteLine("Forwarding to {0}:{1}", settings.addressforward, settings.portforward);
while (true)
{
serverSock.BeginAcceptTcpClient(ae.End(), null);
yield return 1;
TcpClient local = null;
try
{
local = serverSock.EndAcceptTcpClient(ae.DequeueAsyncResult());
local.NoDelay = true;
local.LingerState.Enabled = false;
}
catch (SocketException)
{
Console.WriteLine("A client failed to connect");
}
if(local != null)
{
// handle client
var localAe = new AsyncEnumerator();
localAe.BeginExecute(ServerConnectRemote(localAe, server, ipe, local), localAe.EndExecute, localAe);
}
}
}
示例10: DoBeginAcceptTcpClient
public static void DoBeginAcceptTcpClient(TcpListener listener)
{
listener.BeginAcceptTcpClient(x =>
{
var newClient = listener.EndAcceptTcpClient(x);
string ipaddress = newClient.Client.RemoteEndPoint.ToString();
Console.WriteLine(ipaddress + " has connected.");
DoBeginAcceptTcpClient(listener);
new Thread(() =>
{
string clientName = ipaddress;
string _username = null;
CommandContext _commandContext = null;
TerminalApi _terminalApi;
bool _appRunning = true;
bool _passwordField = false;
var stream = newClient.GetStream();
var streamReader = new StreamReader(stream);
var streamWriter = new StreamWriter(stream);
streamWriter.AutoFlush = true;
streamWriter.WriteLine("Welcome to the U413 telnet server.");
Action<string> invokeCommand = commandString =>
{
var kernel = new StandardKernel(new U413Bindings(false));
_terminalApi = kernel.Get<TerminalApi>();
_terminalApi.Username = _username;
_terminalApi.CommandContext = _commandContext;
streamWriter.WriteLine("Loading...");
var commandResult = _terminalApi.ExecuteCommand(commandString);
// Set the terminal API command context to the one returned in the result.
_commandContext = commandResult.CommandContext;
// If the result calls for the screen to be cleared, clear it.
if (commandResult.ClearScreen)
for (int count = 0; count <= 25; count++)
streamWriter.WriteLine();
// Set the terminal API current user to the one returned in the result and display the username in the console title bar.
_username = commandResult.CurrentUser != null ? commandResult.CurrentUser.Username : null;
//Console.Title = commandResult.TerminalTitle;
// Add a blank line to the console before displaying results.
if (commandResult.Display.Count > 0)
streamWriter.WriteLine();
// Iterate over the display collection and perform relevant display actions based on the type of the object.
foreach (var displayItem in commandResult.Display)
{
if ((displayItem.DisplayMode & DisplayMode.Parse) != 0)
displayItem.Text = U413.Domain.Utilities.BBCodeUtility.ConvertTagsForConsole(displayItem.Text);
streamWriter.WriteLine(displayItem.Text);
}
streamWriter.WriteLine();
//if (!commandResult.EditText.IsNullOrEmpty())
// SendKeys.SendWait(commandResult.EditText.Replace("\n", "--"));
// If the terminal is prompting for a password then set the global PasswordField bool to true.
_passwordField = commandResult.PasswordField;
// If the terminal is asking to be closed then kill the runtime loop for the console.
_appRunning = !commandResult.Exit;
};
invokeCommand("INITIALIZE");
streamWriter.Write("> ");
while (!streamReader.EndOfStream)
{
var commandString = streamReader.ReadLine();
Console.WriteLine("{0}: {1}", (_username ?? clientName), commandString);
invokeCommand(commandString);
streamWriter.Write("> ");
}
}).Start();
}, null);
}
示例11: AcceptClients
private void AcceptClients()
{
try
{
this.listener = new TcpListener(IPAddress.Any, TcpClientReceivePort);
this.listener.Start();
this.listener.BeginAcceptTcpClient((IAsyncResult ar)=>
{
try
{
var tcpClient = listener.EndAcceptTcpClient(ar);
var client = new Client(this, tcpClient);
this.AddClient(client);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
示例12: EstablishConnection
private void EstablishConnection(int listenPort, CancellationToken token)
{
// listen and accept
listener = new TcpListener(IPAddress.Any, listenPort);
token.ThrowIfCancellationRequested();
TcpClient client;
try {
IsListening = true;
listener.Start();
// can be refactored. extract a static method.
var ar = listener.BeginAcceptTcpClient(null, null);
WaitUntilCompleted(ar, NetworkPollingInterval, token);
token.ThrowIfCancellationRequested();
client = listener.EndAcceptTcpClient(ar);
}
finally {
listener.Stop();
IsListening = false;
token.ThrowIfCancellationRequested();
}
// get network stream.
var ns = client.GetStream();
ns.ReadTimeout = NetworkTimeOut;
ns.WriteTimeout = NetworkTimeOut;
networkStream = ns;
IsNetworkConnected = true;
token.ThrowIfCancellationRequested();
}
示例13: Run
/// <summary>
/// Server's main loop implementation.
/// </summary>
/// <param name="log"> The Logger instance to be used.</param>
public Task<Boolean> Run(Logger log)
{
TcpListener srv = null;
try
{
srv = new TcpListener(IPAddress.Loopback, portNumber);
srv.Start();
/////////////////////////////////////////////////////////////////
/////////////////////////////APM/////////////////////////////////
/////////////////////////////////////////////////////////////////
AsyncCallback onAccepted = null;
onAccepted = delegate(IAsyncResult ar)
{
TcpClient socket = null;
try
{
int timeout = (int)ar.AsyncState;
if (timeout == 0)
return;
int time = Environment.TickCount;
using (socket = srv.EndAcceptTcpClient(ar))
{
if(Environment.TickCount - time > timeout)
return;
socket.LingerState = new LingerOption(true, 10);
log.LogMessage(String.Format("Listener - Connection established with {0}.",
socket.Client.RemoteEndPoint));
log.IncrementRequests();
// Instantiating protocol handler and associate it to the current TCP connection
Handler protocolHandler = new Handler(socket.GetStream(), log);
// Synchronously process requests made through de current TCP connection
protocolHandler.Run();
srv.BeginAcceptTcpClient(onAccepted, null);
}
Program.ShowInfo(Store.Instance);
}
catch (SocketException) { Console.WriteLine("Socket error"); }
catch (ObjectDisposedException) { }
};
srv.BeginAcceptTcpClient(onAccepted, 20);
Console.ReadLine();
return null;
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//while (true)
//{
// log.LogMessage("Listener - Waiting for connection requests.");
// using (TcpClient socket = srv.AcceptTcpClient())
// {
// socket.LingerState = new LingerOption(true, 10);
// log.LogMessage(String.Format("Listener - Connection established with {0}.",
// socket.Client.RemoteEndPoint));
// // Instantiating protocol handler and associate it to the current TCP connection
// Handler protocolHandler = new Handler(socket.GetStream(), log);
// // Synchronously process requests made through de current TCP connection
// protocolHandler.Run();
// }
// Program.ShowInfo(Store.Instance);
//}
}
finally
{
log.LogMessage("Listener - Ending.");
srv.Stop();
}
}
示例14: DoConnect
protected override StreamConnection DoConnect(Uri source)
{
TcpClient client = null;
var bind_addr = GetBindAddress(source);
if (bind_addr==null) {
throw new BindErrorException(String.Format("Cannot resolve bind address: {0}", source.DnsSafeHost));
}
var listener = new TcpListener(IPAddress.Any, 1935);
try {
listener.Start(1);
Logger.Debug("Listening on {0}", bind_addr);
var ar = listener.BeginAcceptTcpClient(null, null);
WaitAndProcessEvents(ar.AsyncWaitHandle, stopped => {
if (ar.IsCompleted) {
client = listener.EndAcceptTcpClient(ar);
}
return null;
});
Logger.Debug("Client accepted");
}
catch (SocketException) {
throw new BindErrorException(String.Format("Cannot bind address: {0}", bind_addr));
}
finally {
listener.Stop();
}
if (client!=null) {
this.client = client;
return new StreamConnection(client.GetStream(), client.GetStream());
}
else {
return null;
}
}