using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Hyperz.TcpExample.Server
{
public class Program
{
// config
private static IPAddress ip = IPAddress.Any;
private static short port = 8000;
// end of config
private static Thread thread;
private static TcpListener listener;
static void Main(string[] args)
{
Console.Title = "TCP Server";
listener = new TcpListener(ip, port);
thread = new Thread(worker);
// start the listening thread
thread.Start();
}
static void worker()
{
// listen...
listener.Start();
Console.WriteLine("Waiting for clients!");
while (true)
{
// wait for a client to connect
TcpClient client = listener.AcceptTcpClient();
// client connected
Console.WriteLine("Client {0:x} connected...", client.GetHashCode());
// launch a thread to handle it
ThreadPool.QueueUserWorkItem(tcpClient =>
{
var theClient = (TcpClient)tcpClient;
var stream = theClient.GetStream();
var bufferSize = 4096;
var buffer = new byte[bufferSize];
int count;
// read the client data
while (true)
{
count = 0;
try
{
count = stream.Read(buffer, 0, bufferSize);
}
catch (Exception ex)
{
Console.WriteLine("Error while reading client data: " + ex.Message);
break;
}
if (count > 0)
{
// print the data to the console
Console.WriteLine("{0:x} says: {1}", theClient.GetHashCode(),
Encoding.ASCII.GetString(buffer, 0, count));
}
else break;
}
stream.Close();
theClient.Close();
}, client);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Hyperz.TcpExample.Client
{
public class Program
{
// config
private static string ip = "127.0.0.1";
private static short port = 8000;
// end of config
private static TcpClient client;
private static IPEndPoint endPoint;
static void Main(string[] args)
{
Console.Title = "TCP Client";
endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
client = new TcpClient();
// connect to our server
try
{
client.Connect(endPoint);
}
catch
{
Console.WriteLine("Could not connect to the server :(");
Console.Read();
return;
}
var stream = client.GetStream();
string msg;
byte[] buffer;
// Send messages to the server
while (true)
{
Console.Write("Message: ");
msg = Console.ReadLine();
if (!String.IsNullOrWhiteSpace(msg))
{
buffer = Encoding.ASCII.GetBytes(msg);
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
}
else break;
}
stream.Close();
client.Close();
Console.WriteLine("Connection closed.");
Console.Read();
}
}
}