本文整理汇总了C#中System.Net.Sockets.TcpListener类的典型用法代码示例。如果您正苦于以下问题:C# TcpListener类的具体用法?C# TcpListener怎么用?C# TcpListener使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TcpListener类属于System.Net.Sockets命名空间,在下文中一共展示了TcpListener类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: connect
//Connect to the client
public void connect()
{
if (!clientConnected)
{
IPAddress ipAddress = IPAddress.Any;
TcpListener listener = new TcpListener(ipAddress, portSend);
listener.Start();
Console.WriteLine("Server is running");
Console.WriteLine("Listening on port " + portSend);
Console.WriteLine("Waiting for connections...");
while (!clientConnected)
{
s = listener.AcceptSocket();
s.SendBufferSize = 256000;
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[65535];
int k = s.Receive(b);
ASCIIEncoding enc = new ASCIIEncoding();
Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
//Ensure the client is who we want
if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
{
clientConnected = true;
Console.WriteLine(enc.GetString(b, 0, k));
}
}
}
}
示例2: StartListening
public void StartListening()
{
R = RowacCore.R;
R.Log("[Listener] Starting TCP listener...");
TcpListener listener = new TcpListener(IPAddress.Any, 28165);
listener.Start();
while (true)
{
try
{
var client = listener.AcceptSocket();
#if DEBUG
R.Log("[Listener] Connection accepted.");
#endif
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[1048576]; // for screenshots and tasklists
int size = 0;
while (client.Available != 0)
size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
client.Close();
string request = Encoding.ASCII.GetString(data, 0, size);
#if DEBUG
R.Log(string.Format("Received [{0}]: {1}", size, request));
#endif
ParseRequest(request);
});
childSocketThread.Start();
}
catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
}
}
示例3: ServerContext
public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP)
{
BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished);
ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP);
UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler
UdpServer.JoinMulticastGroup(BroadcastServer.Address);
UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null);
MaxClients = maxclients;
Ip = IPAddress.Any;
this.Port = port;
listener = new TcpListener(Ip, Port);
Clients = new List<ClientContext>(MaxClients);
listener.Start();
BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected);
this.TextStack = TextStack;
}
示例4: FormServeur
// constructeur
public FormServeur()
{
InitializeComponent();
Joueur1 = new Joueur(panelFond, new Point(100, 100),true);
Joueur2 = new Joueur(panelFond, new Point(100, 150),false); // Cette fois les joueurs sont clairements
labelScoreJ1.Text = "0";
labelScoreJ2.Text = "0"; // L'interface n'est plus la même non plus, on dédouble tout.
pBChargeJ1.Maximum = 1000;
pBChargeJ1.Minimum = 0;
pBChargeJ2.Maximum = 1000;
pBChargeJ2.Minimum = 0;
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //on utilise l'adresse ip locale
myList = new TcpListener(ipAd, 8001); //initialisation du listener
myList.Start(); // on écoute sur le port
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint); // Ces trois lignes ci ne servent qu'a controler via la console ce qui se passe.
Console.WriteLine("Waiting for a connection.....");
cl = myList.AcceptTcpClient(); // dés qu'il y a une connection on peut passer a la suite
Console.WriteLine("Connection accepted from " + cl.Client.RemoteEndPoint);
stm = cl.GetStream(); // le flux de données est créé
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadLine();
}
th1 = new Thread(Launch); // on lance le thread qui va lire le flux
th1.Name = "Serveur";
th1.Start();
}
示例5: TCPServer
public TCPServer(int port)
{
listener = new TcpListener(IPAddress.Any, port);
player = new AI(this);
listener.Start();
Start();
}
示例6: EmbeddedSmtpServer
public EmbeddedSmtpServer(IPAddress address, int port = 25)
{
Address = address;
Port = port;
Listener = new TcpListener(Address, port);
}
示例7: button2_Click
private void button2_Click(object sender, EventArgs e)
{
TcpListener serverSocket = new TcpListener(IPAddress.Any, 4955);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
try
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
MessageBox.Show( dataFromClient);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
示例8: Servidor
public Servidor()
{
Console.WriteLine ("Iniciando servidor");
ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
listener = new TcpListener (ipAddress, porta);
listener.Start ();
}
示例9: ModbusTcpSlave_ConnectionClosesGracefully
public void ModbusTcpSlave_ConnectionClosesGracefully()
{
TcpListener slaveListener = new TcpListener(ModbusMasterFixture.TcpHost, ModbusMasterFixture.Port);
slaveListener.Start();
ModbusTcpSlave slave = ModbusTcpSlave.CreateTcp(ModbusMasterFixture.SlaveAddress, slaveListener);
Thread slaveThread = new Thread(slave.Listen);
slaveThread.IsBackground = true;
slaveThread.Start();
using (TcpClient masterClient = new TcpClient(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port))
{
ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient);
master.Transport.Retries = 0;
bool[] coils = master.ReadCoils(1, 1);
Assert.AreEqual(1, coils.Length);
Assert.AreEqual(1, slave.Masters.Count);
}
// give the slave some time to remove the master
Thread.Sleep(50);
Assert.AreEqual(0, slave.Masters.Count);
slaveListener.Stop();
}
示例10: BackupProcess
static void BackupProcess()
{
Console.WriteLine("I am backup!");
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener listener = new TcpListener(ipAddress, port);
listener.Start();
Socket sock = listener.AcceptSocket();
Stream str = new NetworkStream(sock);
StreamReader sr = new StreamReader(str);
string line = "-1";
try
{
while (true)
line = sr.ReadLine();
}
catch(IOException)
{
sr.Close();
listener.Stop();
PrimaryProcess(Convert.ToInt32(line) + 1);
}
}
示例11: Form2
public Form2(String hostPort, Form1 form1)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
dataReadyToSend = new AutoResetEvent(false);
refToForm1 = form1;
// Resolve the local host.
IPHostEntry localHost = Dns.Resolve(Dns.GetHostName());
// Create a local end point for listening.
IPEndPoint localEndPoint = new IPEndPoint(localHost.AddressList[0], 4001);
// Instantiate the TCP Listener.
tcpListener = new TcpListener(localEndPoint);
tcpListener.Start();
tcp = tcpListener.AcceptTcpClient();
ethernetThreadStart = new ThreadStart(this.ThreadProcPollOnEthernet);
pollDevicesEthernetThread = new Thread(ethernetThreadStart);
pollDevicesEthernetThread.Name = "Listener's Receive Thread";
pollDevicesEthernetThread.ApartmentState = System.Threading.ApartmentState.MTA;
pollDevicesEthernetThread.Start();
}
示例12: AcceptClientsAsync
public static async Task AcceptClientsAsync(TcpListener listener, CancellationToken cancel)
{
await Task.Yield();
while (!cancel.IsCancellationRequested)
{
try
{
var timeoutTask = Task.Delay(2000);
var acceptTask = listener.AcceptTcpClientAsync();
await Task.WhenAny(timeoutTask, acceptTask);
if (!acceptTask.IsCompleted)
continue;
var client = await acceptTask;
HandleClientAsync(client, cancel);
}
catch (Exception aex)
{
var ex = aex.GetBaseException();
Console.WriteLine("Accepting error: " + ex.Message);
}
}
}
示例13: TcpServer
public TcpServer(IPAddress ip, ushort port)
{
if (ip == null)
throw new NullReferenceException("ip is null");
_listener = new TcpListener(ip, port);
}
示例14: 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;
}
示例15: HtmlGetServer
public HtmlGetServer(int Port, TcpListener listener)
{
Listener = listener;
if (Listener==null)
Listener = new TcpListener(IPAddress.Any, Port);
Listener.Start();
while (true)
{
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ClientThread), Listener.AcceptTcpClient());
}
catch { }
// Принимаем новых клиентов. После того, как клиент был принят, он передается в новый поток (ClientThread)
// с использованием пула потоков.
/*
// Принимаем нового клиента
TcpClient Client = Listener.AcceptTcpClient();
// Создаем поток
Thread Thread = new Thread(new ParameterizedThreadStart(ClientThread));
// И запускаем этот поток, передавая ему принятого клиента
Thread.Start(Client);
*/
}
}