本文整理汇总了C#中TcpListener类的典型用法代码示例。如果您正苦于以下问题:C# TcpListener类的具体用法?C# TcpListener怎么用?C# TcpListener使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TcpListener类属于命名空间,在下文中一共展示了TcpListener类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
}
}
开发者ID:puninvv,项目名称:university,代码行数:28,代码来源:Server.cs
示例2: BlockingTcpListener
BlockingTcpListener(Loop loop)
: base(loop)
{
TcpListener = new TcpListener(loop);
Listener = TcpListener as Listener;
Handle = TcpListener;
}
开发者ID:txdv,项目名称:LibuvSharp.Blocking,代码行数:7,代码来源:BlockingTcpListener.cs
示例3: handleRequest
/// <summary>
/// Gets request from client, and sends back file/folder to encrypt
/// </summary>
static void handleRequest(TcpListener listener)
{
while (true)
{
int bytesRead;
byte[] buffer = new byte[1024];
string test = null;
Socket s = listener.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
bytesRead = s.Receive(buffer);
char cc = ' ';
Console.WriteLine("Recieved...");
for (int i = 0; i < bytesRead - 1; i++)
{
//Console.Write(Convert.ToChar(buffer[i]));
cc = Convert.ToChar(buffer[i]);
test += cc.ToString();
}
Console.WriteLine(test);
string message = "files encrypted.";
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(message));
s.Close();
Console.WriteLine("sent bytes back");
}
}
开发者ID:joshfermin,项目名称:webroot_encrypt,代码行数:35,代码来源:Program.cs
示例4: Server
/* Constructor */
public Server()
{
//create folder "Plugins" if it doesn't already exists
_PluginLocation=Environment.CurrentDirectory;
_PluginLocation += "\\Plugins\\";
if (!Directory.Exists(_PluginLocation))
{
try
{
Directory.CreateDirectory(_PluginLocation);
}
catch (Exception e)
{
Console.WriteLine(e.Message + "- Plugin-Folder could not be created");
Console.ReadLine();
Environment.Exit(1);
}
}
try
{
//create listener - second param = port
TcpListener = new TcpListener(IPAddress.Any, 8080);
}
catch (Exception) { throw; }
}
开发者ID:broadcastzero,项目名称:bz_hal,代码行数:27,代码来源:Server.cs
示例5: Main
static void Main(string[] args)
{
byte[] quote = Encoding.ASCII.GetBytes("Insanity: doing the same thing over and over again and expecting different results. - Albert Einstein");
var loop = new UVLoop();
var listener = new TcpListener("0.0.0.0", 17, loop);
listener.ConnectionAccepted += (Tcp connection) =>
{
connection.ReadCompleted += (ByteSpan data) =>
{
unsafe
{
fixed (byte* pQuote = quote)
{
connection.TryWrite(new ByteSpan(pQuote, quote.Length));
}
}
};
connection.ReadStart();
};
listener.Listen();
loop.Run();
}
开发者ID:Anniepoh,项目名称:corefxlab,代码行数:27,代码来源:Program.cs
示例6: 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();
}
开发者ID:JnS-Software-LLC,项目名称:CSC153,代码行数:35,代码来源:VerySimpleWebServer.cs
示例7: 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
开发者ID:Fanarito,项目名称:FOR3A,代码行数:31,代码来源:TicTacToeServer.cs
示例8: 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");
}
开发者ID:Lidapow,项目名称:GLTexture,代码行数:29,代码来源:ServerTcp.cs
示例9: Start
public void Start ()
{
tcpListener = new TcpListener (LocalEndPoint);
tcpListener.Start ();
listenThread = new Thread (new ThreadStart (Listen));
listenThread.Start ();
}
开发者ID:mono,项目名称:gert,代码行数:7,代码来源:SocketResponder.cs
示例10: BeginLister
public void BeginLister()
{
while (true)
{
try
{
IPAddress[] Ips = Dns.GetHostAddresses("");
string GetIp = Ips[0].ToString();
Listener = new TcpListener(IPAddress .Parse (GetIp ),8888);
Listener.Start();
CheckForIllegalCrossThreadCalls = false;
butBeginSever.Enabled = false;
this.Text = "服务器已经开启.....";
SocketClient = Listener.AcceptSocket();
NetStream = new NetworkStream(SocketClient );
ServerWriter = new StreamWriter(NetStream );
ServerReader = new StreamReader(NetStream );
if (SocketClient.Connected)
{
MessageBox.Show("客户端连接成功!","服务器消息",MessageBoxButtons .OK ,MessageBoxIcon.Information );
}
}
catch { }
}
}
开发者ID:mayifighting,项目名称:.net,代码行数:25,代码来源:Form1.cs
示例11: Server
public Server()
{
port = 41337;
listener = new TcpListener(port);
otherListener = new TcpListener(41338);
streams = new List<NetworkStream>();
}
开发者ID:ZacJ,项目名称:BroodLord,代码行数:7,代码来源:Server.cs
示例12: StartServer
public void StartServer()
{
TcpListener server = new TcpListener(IPAddress.Parse("192.168.0.13"), 14500);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:14500.{0}Waiting for a connection...", Environment.NewLine);
while (true)
{
Socket client = server.AcceptSocket();
Console.WriteLine("A client connected.");
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[4096];
int size = client.Receive(data);
if (size > 4096) //the packet is too god damn high
{
Console.Write("Client tried to send packet above 4096 bytes");
return;
}
HandlePacket(client,data);
Console.WriteLine("Recieved data:");
for (int i = 0; i < size; i++)
{
Console.Write(Convert.ToChar(data[i]));
}
Console.WriteLine();
client.Close();
});
childSocketThread.Start();
}
}
开发者ID:cosmicpeanut,项目名称:ChatApplication,代码行数:35,代码来源:ListenHandler.cs
示例13: 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;
}
开发者ID:MangoSister,项目名称:VR_Rehearsal,代码行数:31,代码来源:AuthRedirectionServer.cs
示例14: 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;
}
开发者ID:CobaCitizen,项目名称:MyDrives,代码行数:26,代码来源:MainWindow.cs
示例15: DispatchLoop
public DispatchLoop(TcpListener listener, ILogger logger,
IProtocolFactory protoFactory)
{
this.listener = listener;
this.logger = logger;
this.protoFactory = protoFactory;
}
开发者ID:jin55132,项目名称:TCPCSharp,代码行数:7,代码来源:PoolDispatcher.cs
示例16: 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();
}
}
开发者ID:er0dr1guez,项目名称:corefx,代码行数:32,代码来源:NetworkStreamTest.cs
示例17: ListenerSocket
/// <summary>
/// Constructor
/// </summary>
public ListenerSocket()
{
// Init
loadBalancerSocket = new TcpClient();
// Connect to the loadbalancer
Console.Write("Enter the loadbalancer ip: "); // Prompt
loadBalancerSocket.Connect(IPAddress.Parse(Console.ReadLine()), int.Parse(Server.Properties.Resources.LoadBalancerPort));
Logger.ShowMessage(
String.Format("Connected to loadbalancer on: {0}:{1} and {2}:{3}",
((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Address,
((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Port,
((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Address,
((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Port
)
);
Clients = new List<TcpClient>();
messageHandler = new MessageHandler();
// Make the socket listener and thread
Random randomPort = new Random();
listenerSocket = new TcpListener(IPAddress.Any, randomPort.Next(8900, 9000));
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
sendServerPort(loadBalancerSocket, ((IPEndPoint)listenerSocket.LocalEndpoint).Port);
Logger.ShowMessage("Listener initialized.");
Logger.ShowMessage("Listening on: " + ((IPEndPoint)listenerSocket.LocalEndpoint).Address + ":" + ((IPEndPoint)listenerSocket.LocalEndpoint).Port);
// Define the handlers.
PacketManager.DefineOpcodeHandlers();
}
开发者ID:thebillkidy,项目名称:INF202A_DotNetDeel2,代码行数:36,代码来源:ListenerSocket.cs
示例18: Run
public void Run()
{
_broadcaster = new Broadcaster();
IPAddress ip = IPAddress.Parse(_servername);
TcpListener listener = new TcpListener(ip, _port);
/* Gør så at serveren kan skrive input*/
Thread serverInputThread = new Thread(HandleInput);
serverInputThread.Start();
_running = true;
listener.Start();
Console.WriteLine("Skriv \'new\' for at starte en ny auktion.");
while (_running)
{
System.Console.WriteLine("Server klar til bruger");
/* En socket forbinder*/
Socket clientSocket = listener.AcceptSocket();
/* Lav en ny client handler til forbindelsen */
ClientHandler handler = new ClientHandler(clientSocket, _broadcaster);
handler.SetAuction(_auction);
/* Start det i en ny tråd */
Thread clientThread = new Thread(handler.RunClient);
/* Start trådene */
clientThread.Start();
}
}
开发者ID:caddeo,项目名称:Auktionshuset,代码行数:34,代码来源:Server.cs
示例19: Server
public Server(CallResponseQueue queue)
{
this.queue = queue;
this.tcpListener = new TcpListener(IPAddress.Loopback, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
开发者ID:srfoster,项目名称:June,代码行数:7,代码来源:Server.cs
示例20: Start
public void Start(int port)
{
if (listener != null && listener.Server.IsBound)
{
return;
}
this.port = port;
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port);
listener = new TcpListener(ipEnd);
try
{
listener.Start();
running = true;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Push Server Simulator is successfully started on port " + port.ToString());
}
}
catch (Exception e)
{
if (LOGGER.IsErrorEnabled)
{
LOGGER.Error("Error occured while trying to start Push Server Simulator on port " + port.ToString() + " . Message: " + e.Message);
}
}
thread = new Thread(new ThreadStart(listen));
thread.Start();
}
开发者ID:jcamelina,项目名称:oneapi-dot-net,代码行数:32,代码来源:PushServerSimulator.cs
注:本文中的TcpListener类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论