本文整理汇总了C#中TcpListener.Start方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.Start方法的具体用法?C# TcpListener.Start怎么用?C# TcpListener.Start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpListener
的用法示例。
在下文中一共展示了TcpListener.Start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
update_bases();
TcpListener Listen = new TcpListener(IPAddress.Any, 1488);
Listen.Start();
Console.WriteLine("[Server is online]");
int games = 0;
while (true)
{
//кто-то подсоединился
TcpClient Client = Listen.AcceptTcpClient();
Console.Write("[Client connected!]");
NetworkStream ns = Client.GetStream();
//Проверяем, есть ли кто-то в очереди
if (Waiter != null)
{
//в очереди кто-то есть, создаем новую игру
Games.Add(new Game(games++, Waiter, Client, timeOfGame, GenerateWord()));
Waiter = null;
}
else
{
//очеред пуста, закидываем туда клиента
Waiter = Client;
}
}
}
示例2: 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();
}
示例3: 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");
}
示例4: SetUp
} // end method DisplayMessage
// accepts connections from 2 players
public void SetUp()
{
DisplayMessage("Waiting for players...\r\n");
// set up Socket
listener =
new TcpListener(IPAddress.Parse("127.0.0.1"), 50000);
listener.Start();
// accept first player and start a player thread
players[0] = new Player(listener.AcceptSocket(), this, 0);
playerThreads[0] =
new Thread(new ThreadStart(players[0].Run));
playerThreads[0].Start();
// accept second player and start another player thread
players[1] = new Player(listener.AcceptSocket(), this, 1);
playerThreads[1] =
new Thread(new ThreadStart(players[1].Run));
playerThreads[1].Start();
// let the first player know that the other player has connected
lock (players[0])
{
players[0].threadSuspended = false;
Monitor.Pulse(players[0]);
} // end lock
} // end method SetUp
示例5: Main
static void Main(string[] args)
{
TcpListener server = null;
try
{
Int32 port = Convert.ToInt32(args[0]);
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
int numberOfClients = 0;
while (true)
{
Console.WriteLine("Waiting for a connection...");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine((++numberOfClients).ToString() + " Connected!");
HandleClient handleClient = new HandleClient(client);
Thread myThread = new Thread(new ThreadStart(handleClient.Communicate));
myThread.Name = Convert.ToString(numberOfClients);
myThread.IsBackground = true;
myThread.Start();
}
}
finally
{
server.Stop();
}
}
示例6: Start
public void Start()
{
TcpListener listener = new TcpListener(IPAddress, Port);
listener.Start();
Console.WriteLine("Server is running, good luck!");
while (true)
{
var client = new NetworkClient(listener.AcceptTcpClient());
connectedClients.Add(client);
Task.Factory.StartNew(() =>
{
try
{
HandleConnectedClient(client);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
},TaskCreationOptions.LongRunning);
Console.WriteLine("User Connected. Now you have {0} users connected", connectedClients.Count);
}
}
示例7: 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();
}
}
示例8: Main
static void Main(string[] args)
{
if (args.Length != 3) // Test for correct # of args
throw new ArgumentException("Parameter(s): [<Optional properties>]"
+ " <Port> <Protocol> <Dispatcher>");
int servPort = Int32.Parse(args[0]); // Server Port
String protocolName = args[1]; // Protocol name
String dispatcherName = args[2]; // Dispatcher name
TcpListener listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
ILogger logger = new ConsoleLogger(); // Log messages to console
System.Runtime.Remoting.ObjectHandle objHandle =
Activator.CreateInstance(null, protocolName + "ProtocolFactory");
IProtocolFactory protoFactory = (IProtocolFactory)objHandle.Unwrap();
objHandle = Activator.CreateInstance(null, dispatcherName + "Dispatcher");
IDispatcher dispatcher = (IDispatcher)objHandle.Unwrap();
dispatcher.startDispatching(listener, logger, protoFactory);
/* NOT REACHED */
}
示例9: Main
public static void Main()
{
// Setup listener on "localhost" port 12000
IPAddress ipAddr = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener server = new TcpListener(ipAddr, 12000);
server.Start(); // Network driver can now allow incoming requests
// Accept up to 1 client per CPU simultaneously
Int32 numConcurrentClients = Environment.ProcessorCount;
#if false
for (Int32 n = 0; n < numConcurrentClients; n++)
new ClientConnectionApm(server);
#elif true
for (Int32 n = 0; n < numConcurrentClients; n++)
ClientConnectionEnumerator.Start(server);
#else
ClientConnectionSyncStart(server);
// NOTE: Code below won't ever execute because the server CANNOT be stopped cleanly.
#endif
// NOTE: The server CAN be stopped cleanly when doing asynchronous operations
Console.WriteLine("Hit Enter to terminate the server.");
Console.ReadLine();
}
示例10: button1_Click
private void button1_Click(object sender, EventArgs e)
{
try
{
//создание экземпляра класса TcpListener
//данные о хосте и порте читаются
//из текстовых окон
list = new TcpListener(
IPAddress.Parse(textBox1.Text),
Convert.ToInt32(textBox2.Text));
//начало прослушивания клиентов
list.Start();
//создание отдельного потока для чтения сообщения
Thread thread = new Thread(
new ThreadStart(ThreadFun)
);
thread.IsBackground = true;
//запуск потока
thread.Start();
}
catch (SocketException sockEx)
{
MessageBox.Show("Ошибка сокета: " + sockEx.Message);
}
catch (Exception Ex)
{
MessageBox.Show("Ошибка : " + Ex.Message);
}
}
示例11: start
public static void start(int listenPort, System.Action<StreamWriter, string> handleRequest)
{
var server = new TcpListener(IPAddress.Parse("127.0.0.1"), listenPort);
server.Start();
Debug.Log("Start server");
while (Working) {
try {
Thread.Sleep(0);
if (!server.Pending())
continue;
using (var client = server.AcceptTcpClient())
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream, Encoding.UTF8))
using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
Debug.Log("Server Connected");
while (!reader.EndOfStream) {
var line = reader.ReadLine();
handleRequest(writer, line);
}
}
} catch (System.Exception e) {
Debug.Log("RPCServer exception " + e);
}
}
}
示例12: Main
static void Main(string[] args)
{
System.Net.IPAddress localAdd = System.Net.IPAddress.Parse(ipAddress);
TcpListener listener = new TcpListener(localAdd, portNo);
Console.WriteLine("Simple TCP Server");
Console.WriteLine("Listening to ip {0} port: {1}", ipAddress, portNo);
Console.WriteLine("Server is ready.");
// Start listen to incoming connection requests
listener.Start();
// infinit loop.
while (true)
{
// AcceptTcpClient - Blocking call
// Execute will not continue until a connection is established
// We create an instance of ChatClient so the server will be able to
// server multiple client at the same time.
ChatClient user = new ChatClient(listener.AcceptTcpClient());
}
}
示例13: Main
public static void Main() {
IPAddress addr = IPAddress.Parse("0.0.0.0");
int port = 8888;
TcpListener listener = new TcpListener(addr, port);
listener.Start();
for (;;) {
TcpClient connection = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem((_) => {
NetworkStream stream = connection.GetStream();
byte[] data = new byte[256];
int len;
while ((len = stream.Read(data, 0, data.Length)) != 0) {
stream.Write(data, 0, len);
}
stream.Close();
connection.Close();
});
}
}
示例14: Server
public Server()
{
Console.WriteLine("[INFO] Starting Server...");
Console.WriteLine("[INFO] Loading log directory...");
CreateFolder();
Console.WriteLine("[INFO] Log directory loaded");
Console.WriteLine("[INFO] Checking IP Address...");
IPAddress ip;
Console.WriteLine("[INFO] Working IP Address: " + IPAddress.TryParse("127.0.0.1", out ip));
Console.WriteLine("[INFO] Starting Listener Process...");
listener = new TcpListener(ip, 1338);
listener.Start();
Console.WriteLine("[INFO] Listener Process succesfully started at " + ip.ToString() + ":" + 1338);
Console.WriteLine("[INFO] Starting ServerSide Thread...");
Thread thread = new Thread(new ThreadStart(handleServerSideCommands));
thread.Start();
Console.WriteLine("[INFO] Starting Listener Thread...");
Thread thread2 = new Thread(new ThreadStart(handleConnections));
thread2.Start();
}
示例15: Start
public void Start ()
{
tcpListener = new TcpListener (LocalEndPoint);
tcpListener.Start ();
listenThread = new Thread (new ThreadStart (Listen));
listenThread.Start ();
}