本文整理汇总了C#中System.Net.Sockets.TcpListener.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.Stop方法的具体用法?C# TcpListener.Stop怎么用?C# TcpListener.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.TcpListener
的用法示例。
在下文中一共展示了TcpListener.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: NoChannelForkGroup
public void NoChannelForkGroup()
{
using (ShortcutTestClass shortcutTestClass = ParallelizationFactory.GetParallelized<ShortcutTestClass>())
{
TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000);
tcpListener.Start();
shortcutTestClass.NoChannelForkGroup("Test");
int i = 0;
while (!tcpListener.Pending())
{
Thread.Sleep(100);
if (i++ > 20)
{
tcpListener.Stop();
throw new TimeoutException();
}
}
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Expect(new StreamReader(tcpClient.GetStream()).ReadToEnd(), EqualTo("Test"));
tcpClient.Close();
tcpListener.Stop();
}
}
示例2: HandleClients
public static IDisposable HandleClients(TcpListener listener, Func<TcpClient, string, Task> handleClientAccessPolicy, string policyResponse)
{
listener.Start();
var disposableHandler = ThreadPoolScheduler.Instance.ScheduleAsync(async (scheduler, ct) =>
{
var disposable = new BooleanDisposable();
while (!disposable.IsDisposed)
{
var client = await listener.AcceptTcpClientAsync();
await handleClientAccessPolicy(client, policyResponse);
await scheduler.Yield();
}
return disposable;
});
var compositeDisposable = new CompositeDisposable();
compositeDisposable.Add(Disposable.Create(() => listener.Stop()));
compositeDisposable.Add(disposableHandler);
return compositeDisposable;
}
示例3: MassiveInvoke
public void MassiveInvoke()
{
using (ChordTestClass chordTestClass = ParallelizationFactory.GetParallelized<ChordTestClass>())
{
List<TcpListener> tcpListeners = new List<TcpListener>();
for (int i = 0; i < 500; i++)
{
TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000 + i);
tcpListeners.Add(tcpListener);
tcpListener.Start();
chordTestClass.TestMethod4(string.Format("V{0}", i));
chordTestClass.TestMethod5(i);
}
List<string> results = new List<string>();
foreach (TcpListener tcpListener in tcpListeners)
{
int i = 0;
var timeout = 10;
while (!tcpListener.Pending())
{
Thread.Sleep(100);
if (++i > timeout)
{
tcpListener.Stop();
throw new TimeoutException();
}
}
TcpClient tcpClient = tcpListener.AcceptTcpClient();
results.Add(new BinaryReader(tcpClient.GetStream()).ReadString());
tcpClient.Close();
tcpListener.Stop();
}
Debug.Print(string.Format("Received {0} results.", results.Count));
List<string> results1 = new List<string>();
List<string> results2 = new List<string>();
foreach(string value in results)
{
string[] values = value.Split(',');
results1.Add(values[0]);
results2.Add(values[1]);
}
for (int i = 0; i < 500; i++)
{
Expect(results1.Contains(string.Format("V{0}", i)),
string.Format("Missing value1: {0}", i));
Expect(results2.Contains(string.Format("{0}", 23000 + i)),
string.Format("Missing value2: {0}", i));
}
}
}
示例4: start
public void start(object port)
{
listener = new TcpListener((int)port);
listener.Start();
try
{
while (true)
{
if (Form1.stop)
{
Console.WriteLine("broke");
listener.Stop();
break;
}
TcpClient client = listener.AcceptTcpClient();
ClientHandler ch = new ClientHandler(client);
Form1.clients.Add(ch);
Form1.form.Invoke(new Form1.changeText(Form1.form.changeLabel), "Connected:" + Form1.clients.Count);
ch.clientDC += Form1.clientDCed;
Thread t = new Thread(new ThreadStart(ch.start));
t.Start();
}
}
catch (ThreadAbortException t)
{
//this shit isn't called because of the block of accepting tcp
Console.WriteLine("got the abort");
listener.Stop();
}
}
示例5: MassiveInvoke
public void MassiveInvoke()
{
using (ForkTestClass forkTestClass = ParallelizationFactory.GetParallelized<ForkTestClass>())
{
List<TcpListener> tcpListeners = new List<TcpListener>();
for (int i = 0; i < 500; i++)
{
TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000 + i);
tcpListeners.Add(tcpListener);
tcpListener.Start();
forkTestClass.MassiveTest(i.ToString());
}
List<int> results = new List<int>();
foreach (TcpListener tcpListener in tcpListeners)
{
int i = 0;
var timeout = 10;
while (!tcpListener.Pending())
{
Thread.Sleep(100);
if (++i > timeout)
{
tcpListener.Stop();
throw new TimeoutException();
}
}
if(i > timeout)
continue;
TcpClient tcpClient = tcpListener.AcceptTcpClient();
results.Add(new BinaryReader(tcpClient.GetStream()).ReadInt32());
tcpClient.Close();
tcpListener.Stop();
}
Debug.Print(string.Format("Received {0} results.", results.Count));
for (int i = 0; i < 500; i++)
{
Expect(results.Contains(i), string.Format("Missing value: {0}", i));
}
}
}
示例6: file_server
/// <summary>
/// Initializes a new instance of the <see cref="file_server"/> class.
/// Opretter en socket.
/// Venter på en connect fra en klient.
/// Modtager filnavn
/// Finder filstørrelsen
/// Kalder metoden sendFile
/// Lukker socketen og programmet
/// </summary>
private file_server()
{
TcpListener serverSocket = new TcpListener(IPAddress.Parse("10.0.0.1"),PORT);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine("Server Started - Listening for client");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine("Client connected - Waiting for client to input filename");
//Get filename
NetworkStream networkStream = clientSocket.GetStream();
string fileToSend = LIB.readTextTCP (networkStream);
Console.WriteLine("Client trying to retrieve file: " + fileToSend + ". Finding file...");
long fileLength = LIB.check_File_Exists (fileToSend);
if (fileLength != 0) {
Console.WriteLine ("Size of file " + fileLength);
LIB.writeTextTCP (networkStream, "1");
sendFile (fileToSend, fileLength, networkStream);
//Close connection
Console.WriteLine ("File sent - closing connection");
clientSocket.Close ();
serverSocket.Stop ();
Console.WriteLine ("Exit");
} else {
LIB.writeTextTCP (networkStream, "0");
Console.WriteLine ("404 - File not found");
clientSocket.Close ();
serverSocket.Stop ();
}
}
示例7: run
public void run()
{
IPAddress localAdd = IPAddress.Parse(StarryboundServer.config.proxyIP);
TcpListener serversocket = new TcpListener(localAdd, StarryboundServer.config.proxyPort);
serversocket.Start();
StarryboundServer.logInfo("Proxy server has been started on " + localAdd.ToString() + ":" + StarryboundServer.config.proxyPort);
StarryboundServer.serverState = ServerState.Running;
try
{
while (true)
{
TcpClient clientSocket = serversocket.AcceptTcpClient();
new Thread(new ThreadStart(new ClientThread(clientSocket).run)).Start();
}
}
catch (Exception e)
{
StarryboundServer.logException("ListenerThread: " + e.ToString());
}
serversocket.Stop();
StarryboundServer.logException("ListenerThread has failed - No new connections will be possible.");
Console.ReadLine();
}
示例8: GenerateBaseURL
/// <summary>
/// return the base URL with finding unused TCP port number.
/// </summary>
private static string GenerateBaseURL()
{
var portNumbers = getRandoms(8000, 8999);
var fixedPortNumber = ConfigurationManager.AppSettings["shell:FixedPortNumber"];
if (string.IsNullOrEmpty(fixedPortNumber) == false)
{
portNumbers = new[] { int.Parse(fixedPortNumber) }.Concat(portNumbers);
}
var port = portNumbers.First(p =>
{
var listener = new TcpListener(IPAddress.Loopback, p);
try
{
listener.Start();
return true;
}
catch (Exception) { }
finally
{
listener.Stop();
}
return false;
});
var baseURL = $"http://localhost:{port}/";
return baseURL;
}
示例9: Start
public void Start(Action<TcpClient, byte[]> onData, Action<TcpClient> onDisconnect)
{
TcpListener listener = new TcpListener(port);
listener.Start();
running = true;
AutoResetEvent are = new AutoResetEvent(false);
agent = new Agent<Action>(
() => { },
() => { },
nextaction =>
{
nextaction();
if (running)
{
return NextAction.WaitForNextMessage;
}
are.Set();
return NextAction.Finish;
});
agent.Start();
agent.SendMessage(() => { StartAccepting(listener, onData, onDisconnect); });
are.WaitOne();
listener.Stop();
}
示例10: ProcessMessageTest
public void ProcessMessageTest()
{
// setup the client configurations
TcpSendEndpoint sendEndpoint = new TcpSendEndpoint();
TcpSendOptions options = new TcpSendOptions();
options.Endpoint = new IPEndPoint(IPAddress.Loopback, 6789);
sendEndpoint.Initialize(null, options);
// start a tcp listener
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 6789));
listener.Start();
// start the enpoint for processing
sendEndpoint.StartProcessing();
// send messages
byte[] data = { 0x41, 0x41, 0x41, 0x41 };
sendEndpoint.ProcessMessage(null, data); // AAAA
// assert listener for receive of messages
var socket = listener.AcceptSocket();
byte[] readData = new byte[8];
Assert.AreEqual(8, socket.Receive(readData, 0, 8, SocketFlags.None));
// close the client
sendEndpoint.StopProcessing();
// close the server
listener.Stop();
// assert data is valid
byte[] expectedData = { TcpSendOptions.SOH, TcpSendOptions.STX, 0x41, 0x41, 0x41, 0x41, TcpSendOptions.ETX, TcpSendOptions.EOT };
Assert.IsTrue(expectedData.SequenceEqual(readData));
}
示例11: listen
public void listen()
{
while (true)
{
portchanged = false;
listener = new TcpListener(IPAddress.Any, Convert.ToInt32(settingsg.port));
listener.Start();
while (!portchanged)
{
TcpClient s = listener.AcceptTcpClient();
lastip = ((IPEndPoint)s.Client.RemoteEndPoint).Address.ToString();
//if (lastip.StartsWith("127") || lastip.StartsWith("192.168"))
{
hpr p = new hpr(s, this);
new Thread(new ThreadStart(p.process)).Start();
}
//else
{
//s.Close();
//ff.append(String.Format("{1}- Rejected external client {0}", lastip, DateTime.Now));
}
}
listener.Stop();
}
}
示例12: Main
static void Main(string[] args)
{
bool done = false;
//TcpListener listener = new TcpListener(portNum); //����VS2005 MSDN �˷����Ѿ���ʱ������ʹ��
// IPEndPoint�� �������ʶΪIP��ַ�Ͷ˿ں�
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, portNum));
listener.Start();
while (!done)
{
Console.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream ns = client.GetStream();
byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
try
{
ns.Write(byteTime, 0, byteTime.Length);
ns.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
listener.Stop();
}
示例13: FindFreePort
public int FindFreePort(int startingPort)
{
Exception lastException = null;
for (int i = startingPort; i < 65535; i++)
{
try
{
var listener = new TcpListener(IPAddress.Loopback, i);
listener.Start();
listener.Stop();
logger.Debug("Found free port: {0}", i);
return i;
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.AddressAlreadyInUse)
lastException = e;
else
throw;
}
}
throw lastException;
}
示例14: StopTcpListener
public void StopTcpListener ()
{
var listener = new TcpListener (IPAddress.Loopback, 0);
listener.Start ();
listener.Stop ();
Assert.Throws<InvalidOperationException> (() => listener.AcceptTcpClient ());
}
示例15: StartThread
public void StartThread()
{
Print("Server started");
var listner=new TcpListener(IPAddress.Any, port);
listner.Start();
CvarcClient cvarcClient = null;
while(true)
{
while (!listner.Pending())
{
if (exitRequest)
{
if (cvarcClient != null)
cvarcClient.Close();
listner.Stop();
return;
}
Thread.Sleep(1);
}
var client = listner.AcceptTcpClient();
Print("Client accepted");
if (cvarcClient != null)
cvarcClient.Close(); // этот метод должен внутри CvarcClient устанавливать флаг, при котором цикл внутри Read заканчивается исключением
cvarcClient = new CvarcClient(client);
if (ClientConnected != null)
ClientConnected(cvarcClient);
}
}