本文整理汇总了C#中TcpListener.AcceptTcpClient方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.AcceptTcpClient方法的具体用法?C# TcpListener.AcceptTcpClient怎么用?C# TcpListener.AcceptTcpClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpListener
的用法示例。
在下文中一共展示了TcpListener.AcceptTcpClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ClientConnectionSync
private static void ClientConnectionSync(TcpListener server)
{
using (TcpClient client = server.AcceptTcpClient()) {
using (Stream stream = client.GetStream()) {
Byte[] inputData = new Byte[1];
Int32 numBytesRead = stream.Read(inputData, 0, 1);
if (numBytesRead == 0) {
// Client closed connection; abandon this client request
inputData = null;
} else {
// Resize the array to 1 bytes (for length) + the size of the data
Array.Resize(ref inputData, 1 + inputData[0]);
// Read in all the data (after the length byte)
for (Int32 bytesReadSoFar = 0; bytesReadSoFar < inputData.Length - 1; ) {
Int32 bytesReadThisTime = stream.Read(inputData, 1 + bytesReadSoFar,
inputData.Length - (bytesReadSoFar + 1));
if (bytesReadThisTime == 0) {
// Client closed connection; abandon this client request
inputData = null;
break;
}
bytesReadSoFar += bytesReadThisTime;
}
// Process the data and return the result
Byte[] outputData = ProcessData(inputData);
stream.Write(outputData, 0, outputData.Length);
}
}
}
}
示例2: 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;
}
示例3: 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();
});
}
}
示例4: 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();
}
}
示例5: 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);
}
}
}
示例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: 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();
}
示例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");
}
示例9: 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();
}
示例10: 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();
}
}
示例11: Main
public static void Main(String[] args)
{
TcpListener server = new TcpListener(int.Parse(args[0]));
server.Start();
while(true) {
TcpClient client = server.AcceptTcpClient();
new ClientThread(client);
}
}
示例12: TcpServerRun
public void TcpServerRun(){
tcpListener = new TcpListener (IPAddress.Any, 30000);
tcpListener.Start ();
while(true){
TcpClient client = tcpListener.AcceptTcpClient();
Thread tcpHandlerThread = new Thread(new ParameterizedThreadStart(tcpHandler));
tcpHandlerThread.Start(client);
}
}
示例13: 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();
}
}
示例14: Main
public static void Main()
{
TcpListener server = null;
try
{
Int32 port = 777;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
bool running = true;
while (running)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
client.Close();
if (data == "EXIT") running = false;
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
}
示例15: Main
public static void Main()
{
TcpListener server=null;
try
{
IPHostEntry iph = Dns.GetHostEntry(Dns.GetHostName());
server = new TcpListener(iph.AddressList[1], 13000);
server.Start();
Console.WriteLine("Server Started at {0}",iph.AddressList[1]);
while (true)
{
TcpClient Client = server.AcceptTcpClient();
client cl = new client();
IPEndPoint IPend = (IPEndPoint)Client.Client.RemoteEndPoint;
cl.ip = IPend.Address.ToString();
StreamReader sr = new StreamReader(Client.GetStream());
char[] data = new char[20];
sr.Read(data, 0, data.Length);
cl.name = new string(data);
cl.name=cl.name.Substring(0,cl.name.IndexOf('\0'));
Console.WriteLine(cl.name+" "+cl.ip);
StreamWriter sw = new StreamWriter(Client.GetStream());
sw.AutoFlush = true;
StringBuilder names = new StringBuilder();
StringBuilder ips = new StringBuilder();
foreach (client c in clients)
{
names.Append(c.name + "*");
ips.Append(c.ip + "*");
}
string write = names + "&" + ips;
if (clients.Count == 0)
write = "No One Available*&";
sw.Write(write.ToCharArray());
clients.Add(cl);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
Console.Read();
}
finally
{
server.Stop();
}
}