本文整理汇总了C#中System.Net.Sockets.TcpListener.Pending方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.Pending方法的具体用法?C# TcpListener.Pending怎么用?C# TcpListener.Pending使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.TcpListener
的用法示例。
在下文中一共展示了TcpListener.Pending方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ChatServer
public ChatServer()
{
// create nickName & nickNameByConnect variables
nickName = new Hashtable(100);
nickNameByConnect = new Hashtable(100);
// initialise chatServer with at the local IP address host on port 4296
chatServer = new TcpListener(host, 4296);
// check to see that the server is running
// visual indication server is running
Console.WriteLine("Server Running");
//keep running
while (true)
{
// start the server
chatServer.Start();
// if there are connections pending
if (chatServer.Pending())
{
// accept the connection
Chat.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient();
// display message to client
Console.WriteLine("You are now connected");
// create a new DoCommunicate object
DoCommunicate comm = new DoCommunicate(chatConnection);
}
}
}
示例2: AddClients
/// <summary>
/// This method will constantly run as a thread. It currently sends a multicast to the network every second, informing
/// computers on the network that it is there. When a client sees this, it will send a message to the server and the client
/// will be added to the clients list.
/// </summary>
public static void AddClients()
{
clients = new List<ClientThread>();
TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
serverSocket.Start();
while (true)
{
TcpClient tempClientSocket = new TcpClient();
tempClientSocket.ReceiveTimeout = 300;
SendMulticast();
//Check and see if a computer is trying to connect.
//If not, then sleep, and resend multicast in a second
if (serverSocket.Pending())
{
tempClientSocket = serverSocket.AcceptTcpClient();
ClientThread c = new ClientThread(tempClientSocket,null);
clients.Add(c);
Console.WriteLine("Connected to " + c.GetClientIP() + " :: "+c.GetPort());
}
else {
Thread.Sleep(1000); //Sleep for a second, before sending the next multicast.
}
}
}
示例3: 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();
}
}
示例4: Main
static void Main(string[] args)
{
var settings = ConfigurationManager.AppSettings;
var port = settings["COM_PORT"];
var speed = Convert.ToInt32(settings["COM_SPEED"]);
var tcpPort = Convert.ToInt32(settings["TCP_PORT"]);
serial = new SerialManager(port, speed);
Console.WriteLine("UART: " + port + " - " + speed);
server = new HardwareTcpServer(tcpPort);
server.OnServerState += server_OnServerState;
server.OnClientState += server_OnClientState;
server.OnData += server_OnData;
serial.OnReceive += serial_OnReceive;
serial.OnStateChange += serial_OnStateChange;
serial.Connect();
// bridge = new HttpToUartBridge(6200);
TcpListener listener = new TcpListener(IPAddress.Parse("188.127.233.35"), tcpPort);
listener.Start();
Console.WriteLine("TCP: " + tcpPort);
while (Thread.CurrentThread.ThreadState == ThreadState.Running)
{
Console.WriteLine("Listening " + tcpPort);
while (!listener.Pending())
{
Thread.Sleep(300);
}
server.AcceptTcpClient(listener.AcceptSocket());
}
Console.WriteLine("Stopped");
listener.Stop();
server.Close();
serial.Close();
}
示例5: Listen
private void Listen()
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, ListenPort);
tcpListener.Start();
TcpClient client = null;
try
{
while (!CloseClass)
{
if (!tcpListener.Pending())
{
Thread.Yield();
}
else
{
client = tcpListener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(x => returnMethod(client));
}
}
}
finally
{
if (client != null)
{
client.Close();
}
tcpListener.Stop();
}
}
示例6: 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);
}
}
示例7: Chatserver
public Chatserver()
{
//create our nickname and nickname by connection variables
nickName = new Hashtable(100);
nickNameByConnect = new Hashtable(100);
//create our TCPListener object
chatServer = new System.Net.Sockets.TcpListener(4296);
//check to see if the server is running
//while (true) do the commands
while (true)
{
//start the chat server
chatServer.Start();
//check if there are any pending connection requests
if (chatServer.Pending())
{
//if there are pending requests create a new connection
Chat.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient();
//display a message letting the user know they're connected
Console.WriteLine("You are now connected");
//create a new DoCommunicate Object
DoCommunicate comm = new DoCommunicate(chatConnection);
}
}
}
示例8: run
public void run()
{
Debug.Log("ACCEPTOR THREAD: Starting Tcp Listener");
try
{
tcpListener = new TcpListener(IPAddress.Any, 4444);
tcpListener.Start ();
//new Thread (new ThreadStart (DiscoveryThread.Instance.run)).Start();
Debug.Log("ACCEPTOR THREAD: Waiting for clients...");
while (_isRunning) {
while (!tcpListener.Pending()) {
Thread.Sleep (1000);
}
Debug.Log("ACCEPTOR THREAD: Client accepted!");
ConnectionThread newconnection = new ConnectionThread(tcpListener);
runningConnections.Add(newconnection);
new Thread (new ThreadStart (newconnection.HandleConnection)).Start();
Thread.Sleep(100);
}
}
catch (Exception e)
{
Debug.LogError (e.ToString());
}
Debug.Log("ACCEPTOR THREAD: TCP Requesting Stop from " + runningConnections.Count + " open connections");
foreach (ConnectionThread connection in runningConnections) {
connection.RequestStop();
}
Debug.Log("ACCEPTOR THREAD: Ending...");
}
示例9: Start
public static void Start(int port)
{
TcpListener listener = new TcpListener (IPAddress.Loopback, port);
listener.Start ();
while (run) {
while (!listener.Pending() && run) {
Thread.Sleep (200);
}
if (!run)
break;
Socket newSocket = listener.AcceptSocket ();
Thread thread = new Thread (new ParameterizedThreadStart (Handshaker));
int id = 0;
lock (serviceThreads) {
id = serviceThreads.Count > 0 ? serviceThreads.Keys.Max () + 1 : 0;
serviceThreads.Add (id, thread);
}
thread.Start (new object[] { id, newSocket });
}
}
示例10: ReceiveTCP
public static void ReceiveTCP(int portN)
{
TcpListener Listener = null;
try
{
Listener = new TcpListener(IPAddress.Any, portN);
Listener.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
int BufferSize = 4096;
byte[] RecData = new byte[BufferSize];
int RecBytes;
for (; ; )
{
TcpClient client = null;
NetworkStream netstream = null;
//Status = string.Empty;
try
{
string message = "Accept the Incoming File ";
string caption = "Incoming Connection";
//MessageBoxButtons buttons = MessageBoxButtons.YesNo;
//DialogResult result;
if (Listener.Pending())
{
client = Listener.AcceptTcpClient();
netstream = client.GetStream();
//Status = "Connected to a client\n";
//result = MessageBox.Show(message, caption, buttons);
Console.WriteLine("Connected to a sender");
string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string SaveFileName = dirPath+"\\"+string.Format("RecvdFile-{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
if (SaveFileName != string.Empty)
{
int totalrecbytes = 0;
FileStream Fs = new FileStream(SaveFileName, FileMode.OpenOrCreate, FileAccess.Write);
while ((RecBytes = netstream.Read(RecData, 0, RecData.Length)) > 0)
{
Fs.Write(RecData, 0, RecBytes);
totalrecbytes += RecBytes;
}
Fs.Close();
}
netstream.Close();
client.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//netstream.Close();
}
}
}
示例11: Listen
public void Listen()
{
TcpListener listener = new TcpListener(IPAddress.Any,
Convert.ToInt32(ConfigurationManager.AppSettings["tcpPort"]));
try
{
listener.Start();
int clientNr = 0;
OnLogged("Waiting for a connection...");
while (continueProcess)
{
if (listener.Pending())
{
TcpClient handler = listener.AcceptTcpClient();
if (handler != null)
{
OnLogged("Client #{0} accepted", ++clientNr);
ClientHandler client = new ClientHandler(handler);
client.Logged += Logged;
connectionPool.Enqueue(client);
}
}
Thread.Sleep(100);
}
}
finally
{
listener.Stop();
}
}
示例12: Replyer
/// <summary>
/// Monitor pentru starea firului de execuţie de rezolvare a cererilor.
/// </summary>
//private ManualResetEvent tcpClientConnected;
/// <param name="iTransformer">Transformatorul de cereri în răspuns</param>
/// <param name="port">Portul pe care se ascultă</param>
public Replyer(ITransformer iTransformer, int port)
{
this.iTransformer = iTransformer;
TcpListener tcpl = new TcpListener(IPAddress.Any, port);
tcpl.Start();
while (true) {
try {
while (!tcpl.Pending()) {
Thread.Sleep(1000);
}
TcpClient client = tcpl.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(receiveTransformAndSendFeedback, client);
}
catch (ThreadAbortException) {
tcpl.Stop();
return;
}
}
}
示例13: Listen
public void Listen(int port)
{
TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
try
{
while (true)
{
if (serverSocket.Pending())
{
clientSocket = serverSocket.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(o => ProcessRequest(clientSocket));
}
else
{
Thread.Sleep(100);
}
}
}
catch (ThreadAbortException)
{
Console.WriteLine(" >> Server Ended");
t = null;
}
}
示例14: 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));
}
}
}
示例15: Main
static void Main(string[] args)
{
ServerConfig.ParseConfig(args);
Logger.InitWithName(ServerConfig.Name);
Thread.CurrentThread.Name = "SERVER";
var slave = new TcpListener(ServerConfig.ListenPort);
try
{
try
{
slave.Start(10);
}
catch
{
throw new Exception(@"Невозможно открыть сокет №" + ServerConfig.ListenPort.ToString());
}
while (true)
{
TcpClient connect = null;
if (slave.Pending())
{
try
{
connect = slave.AcceptTcpClient();
}
catch
{
}
}
if (connect == null) {Thread.Sleep(500); continue;}
if (connect.Connected)
{
Terminal terminal = new Terminal(connect);
Thread thread = new Thread(Terminal.DoWork);
thread.Start(terminal);
}
Thread.Sleep(0);
}
}
catch (OutOfMemoryException e)
{
Logger.WriteMessage(Logger.EventID.ServiceCrash, @"ПЕРЕПОЛНЕНИЕ ВИРТУАЛЬНОЙ ПАМЯТИ: " + e.ToString());
}
catch (Exception ex)
{
Logger.WriteMessage(Logger.EventID.ServiceCrash, ex.ToString());
}
finally
{
slave.Stop();
Logger.Close();
}
}