本文整理汇总了C#中TcpListener.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.Stop方法的具体用法?C# TcpListener.Stop怎么用?C# TcpListener.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpListener
的用法示例。
在下文中一共展示了TcpListener.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RunWithConnectedNetworkStreamsAsync
/// <summary>
/// Creates a pair of connected NetworkStreams and invokes the provided <paramref name="func"/>
/// with them as arguments.
/// </summary>
private static async Task RunWithConnectedNetworkStreamsAsync(Func<NetworkStream, NetworkStream, Task> func)
{
var listener = new TcpListener(IPAddress.Loopback, 0);
try
{
listener.Start(1);
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new TcpClient(clientEndpoint.AddressFamily))
{
Task<TcpClient> remoteTask = listener.AcceptTcpClientAsync();
Task clientConnectTask = client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
await Task.WhenAll(remoteTask, clientConnectTask);
using (TcpClient remote = remoteTask.Result)
using (NetworkStream serverStream = remote.GetStream())
using (NetworkStream clientStream = client.GetStream())
{
await func(serverStream, clientStream);
}
}
}
finally
{
listener.Stop();
}
}
示例2: Main
static void Main(string[] arg)
{
SecurePlugin.Factory factory = new SecurePlugin.Factory ("test-pub-priv-key.snk");
SecurePlugin.IDPair pair = factory.BuildSecurePlugin (arg[0]);
SecurePlugin.DataBase db = new SecurePlugin.DataBase();
db.Insert (pair.license_id, pair.plugin_id);
db.Print();
TcpClient client = null;
TcpListener server = null;
try
{
server = new TcpListener (IPAddress.Parse ("127.0.0.1"), 6969);
server.Start();
while (true)
ThreadPool.QueueUserWorkItem
(new LicenseHandler (server.AcceptTcpClient (), db).Start);
}
catch (SocketException e)
{
Console.WriteLine ("SocketException: {0}", e);
}
finally
{
server.Stop();
}
}
示例3: Run
public static void Run()
{
var listener = new TcpListener(IPAddress.Loopback, 8181);
listener.Start();
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
Console.WriteLine(reader.ReadLine());
Console.WriteLine(reader.ReadLine());
Console.WriteLine(reader.ReadLine());
Console.WriteLine(reader.ReadLine());
Console.WriteLine(reader.ReadLine());
Console.WriteLine(reader.ReadLine());
writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
writer.WriteLine("Upgrade: WebSocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("WebSocket-Origin: http://localhost:8080");
writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
writer.WriteLine("");
}
listener.Stop();
}
示例4: Start
public int Start ()
{
bool processed;
Console.WriteLine ("Touch.Unit Simple Server listening on: {0}:{1}", Address, Port);
server = new TcpListener (Address, Port);
try {
server.Start ();
do {
using (TcpClient client = server.AcceptTcpClient ()) {
processed = Processing (client);
}
} while (!AutoExit || !processed);
}
catch (Exception e) {
Console.WriteLine ("[{0}] : {1}", DateTime.Now, e);
return 1;
}
finally {
server.Stop ();
}
return 0;
}
示例5: Main
public static void Main(String[] args)
{
TcpListener server=null;
try {
//Echo servers listen on port 7
int portNumber = 7;
//Echo server first binds to port 7
server = new TcpListener(portNumber);
//Server starts listening
server.Start();
//Echo server loops forever, listening for clients
for(;;) {
//Accept the pending client connection and return a client
//initialized for communication
//This method will block until a connection is made
EchoServer es = new EchoServer(server.AcceptTcpClient());
//Allow this conversation to run in a new thread
Thread serverThread = new Thread(
new ThreadStart(es.Conversation));
serverThread.Start();
//Loop back up and wait for another client
//Another thread is servicing this client
}
} catch (Exception e) {
Console.WriteLine(e+" "+e.StackTrace);
} finally {
//Release the port and stop the server
server.Stop();
}
}
示例6: Main
static void Main(string[] args)
{
if (args.Length != 1) // Test for correct # of args
throw new ArgumentException("Parameters: <Port>");
int port = Int32.Parse(args[0]);
// Create a TCPListener to accept client connections
TcpListener listener = new TcpListener(IPAddress.Any, port);
listener.Start();
TcpClient client = listener.AcceptTcpClient(); // Get client connection
// Receive text-encoded quote
ItemQuoteDecoder decoder = new ItemQuoteDecoderText();
ItemQuote quote = decoder.decode(client.GetStream());
Console.WriteLine("Received Text-Encoded Quote:");
Console.WriteLine(quote);
// Repeat quote with binary-encoding, adding 10 cents to the price
ItemQuoteEncoder encoder = new ItemQuoteEncoderBin();
quote.unitPrice += 10; // Add 10 cents to unit price
Console.WriteLine("Sending (binary)...");
byte[] bytesToSend = encoder.encode(quote);
client.GetStream().Write(bytesToSend, 0 , bytesToSend.Length);
client.Close();
listener.Stop();
}
示例7: GetFreePort
public static int GetFreePort()
{
TcpListener tcpListener = default(TcpListener);
int port = 0;
try
{
var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
tcpListener = new TcpListener(ipAddress, 0);
tcpListener.Start();
string s = tcpListener.LocalEndpoint.ToString();
s = s.Substring(s.IndexOf("]:")+2);
port = int.Parse(s);
return port;
}
catch (SocketException)
{
}
finally
{
if (tcpListener != null)
tcpListener.Stop();
}
return port;
}
示例8: StartServer
/// <summary>
/// Start a HTTP server.
/// </summary>
/// <param name="port">Port number.</param>
public bool StartServer(int port)
{
try
{
Debug.Log("Starting a server...");
server = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
server.Start();
listenThread = new Thread(Listen);
listenThread.Start();
Debug.Log("The server is started.");
}
catch (Exception e)
{
Debug.LogError(e);
if (server != null)
server.Stop();
server = null;
return false;
}
return true;
}
示例9: Execute
protected override void Execute()
{
TcpListener server = null;
NetworkStream stream = null;
TcpClient client = null;
server = new TcpListener(8080);
server.Start();
byte[] buffer = new byte[150 * 1024];
int i = 0;
logger.Log("Thread Start");
for(;;){
client = server.AcceptTcpClient();
stream = client.GetStream();
while ((i = stream.Read(buffer, 0, buffer.Length)) != 0){
retrievedPacket(i, buffer);
i = 0;
if(terminate) break;
}
client.Close();
Thread.Sleep(1000 / 30);
if(terminate) break;
}
server.Stop();
logger.Log("Thread Stop");
}
示例10: Main
public static void Main(String[] args)
{
TcpListener server = new TcpListener(int.Parse(args[0]));
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
String s = reader.ReadLine();
String[] strings = s.Split();
StreamWriter writer;
if (strings[0] != "GET") {
writer = new StreamWriter(stream);
writer.WriteLine
("HTTP/1.0 501 Not Implemented");
writer.WriteLine();
} else {
String filename = strings[1];
while(reader.ReadLine() != "");
writer = new StreamWriter(stream);
writer.WriteLine("HTTP/1.0 200 OK");
writer.WriteLine("Content-type: text/plain");
writer.WriteLine();
StreamReader file = new StreamReader(filename);
String z = file.ReadToEnd();
writer.WriteLine(z);
writer.Flush();
writer.Close();
file.Close();
}
client.Close();
stream.Close();
reader.Close();
writer.Close();
server.Stop();
}
示例11: Main
static void Main(string[] args)
{
TcpListener tcpl = null;
TcpClient tcpc = null;
NetworkStream stream = null;
try
{
tcpl = new TcpListener(IPAddress.Any, 9999);
tcpl.Start();
Console.Write("Waiting for client... ");
tcpc = tcpl.AcceptTcpClient();
Console.WriteLine("ok");
stream = tcpc.GetStream();
ProtocolSI protocol = new ProtocolSI();
ProtocolSICmdType command;
byte[] packet;
do
{
stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
command = protocol.GetCmdType();
switch (protocol.GetCmdType())
{
case ProtocolSICmdType.NORMAL:
Console.WriteLine("inteiro: " + protocol.GetIntFromData().ToString());
break;
case ProtocolSICmdType.DATA:
Console.WriteLine("string: " + protocol.GetStringFromData());
break;
case ProtocolSICmdType.EOT:
Console.WriteLine("end");
break;
default:
Console.WriteLine("not expected");
break;
}
} while (command != ProtocolSICmdType.EOT);
packet = protocol.Make(ProtocolSICmdType.ACK);
stream.Write(packet, 0, packet.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
finally
{
Console.WriteLine("disconnected");
if (stream != null) stream.Dispose();
if (tcpc != null) tcpc.Close();
if (tcpl != null) tcpl.Stop();
}
}
示例12: GetRandomUnusedPort
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
示例13: StartListening
public static void StartListening()
{
ClientSockets = new ArrayList();
ThreadReclaim = new Thread(new ThreadStart(Reclaim));
ThreadReclaim.Start();
TcpListener listener = new TcpListener(IPAddress.Any, portNum);
try
{
listener.Start();
int Cycle = 3;
int ClientNbr = 0;
Console.WriteLine("Waiting for a connection...");
while (Cycle > 0)
{
TcpClient handler = listener.AcceptTcpClient();
if (handler != null)
{
Console.WriteLine("Client#{0} accepted!", ++ClientNbr);
lock (ClientSockets.SyncRoot)
{
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
ClientList.Add(handler);
}
--Cycle;
}
else
break;
}
listener.Stop();
ContinueReclaim = false;
ThreadReclaim.Join();
foreach (Object Client in ClientSockets)
{
((ClientHandler)Client).Stop();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
示例14: Create_Success
public void Create_Success()
{
// NOTE: the '0' below will cause the TcpListener to bind to an anonymous port.
TcpListener listener = new TcpListener(IPAddress.IPv6Any, 0);
listener.Server.DualMode = true;
listener.Start();
listener.Stop();
}
示例15: Main
public static void Main(String[] args)
{
StreamReader sr=null;
StreamWriter sw=null;
TcpClient client=null;
TcpListener server=null;
try {
//Echo servers listen on port 7
int portNumber = 7;
//Echo server first binds to port 7
server = new TcpListener(portNumber);
//Server starts listening
server.Start();
//Echo server loops forever, listening for clients
for(;;) {
Console.WriteLine("Waiting for a connection....");
//Accept the pending client connection and return a client
//initialized for communication
//This method will block until a connection is made
client = server.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
//Make a user-friendly StreamReader from the stream
sr=new StreamReader(client.GetStream());
//Make a user-friendly StreamWriter from the stream
sw=new StreamWriter(client.GetStream());
String incoming=sr.ReadLine();
while (incoming!=".") {
Console.WriteLine("Message received: "+incoming);
sw.WriteLine(incoming);
sw.Flush();
Console.WriteLine("Message Sent back: " + incoming);
incoming=sr.ReadLine();
}
Console.WriteLine("Client sent '.': closing connection.");
sr.Close();
sw.Close();
client.Close();
}
} catch (Exception e) {
Console.WriteLine(e+" "+e.StackTrace);
} finally {
if (sr!=null) sr.Close();//check if the stream reader is present - if it is, close it
if (sw!=null) sw.Close();//check if the stream writer is present - if it is, close it
if (client!=null) client.Close();
//Release the port and stop the server
server.Stop();
}
}