using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TCPnetwork
{
class Program
{
public static ManualResetEvent TcpListenerEndEvent = new ManualResetEvent(false);
public static ManualResetEvent TcpClientClosedEvent = new ManualResetEvent(false);
private const uint SIZE_OF_READ_BUFFER = 100;
private const long SIZE_OF_MAX_READ = 200;
static void Main(string[] args)
{
StartServer();
}
private static void StartServer(){
try
{
/* Initializes the Listener */
TcpListener tServer = new TcpListener(IPAddress.Parse("192.168.1.34"), 8001);
/* Start Listeneting at the specified port */
tServer.Start();
TcpListenerEndEvent.Reset();
while (!TcpListenerEndEvent.WaitOne(0))
{
BeginAccecptATcpClient(tServer);
}
//Console.WriteLine(string.Concat(tServer.LocalEndpoint, " will been termined!"));
tServer.Stop();
//Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
private static void BeginAccecptATcpClient(TcpListener tServer)
{
// Set the event to nonsignaled state.
TcpClientClosedEvent.Reset();
tServer.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), tServer);
TcpClientClosedEvent.WaitOne();
}
private static void DoAcceptTcpClientCallback(IAsyncResult ar)
{
TcpClient client = null;
try
{
// Get the listener that handles the client request.
TcpListener listener = (TcpListener)ar.AsyncState;
client = listener.EndAcceptTcpClient(ar);
if (client != null)
{
if (client.Client != null)
{
//Console.WriteLine("Connection accepted from " + client.Client.RemoteEndPoint);
}
Thread th = new Thread(new ParameterizedThreadStart(ThreadWork));
th.Start(client);
}
}
catch (SocketException se) { Console.WriteLine(se.StackTrace); }
catch (Exception e) { Console.WriteLine(e.StackTrace); }
finally {}
}
private static void ThreadWork(object param)
{
TcpClient s = param as TcpClient;
NetworkStream stream = s.GetStream();
try
{
byte[] b = new byte[SIZE_OF_READ_BUFFER];
int numberOfBytesRead = 0;
MemoryStream dummyByteStream = new MemoryStream();
long bytesToRead = SIZE_OF_MAX_READ;
do
{
if (stream.DataAvailable)
{
int len = (int)(bytesToRead - dummyByteStream.Length);
if (len > b.Length) len = b.Length;
numberOfBytesRead = stream.Read(b, 0, len);
dummyByteStream.Write(b, 0, numberOfBytesRead);
}
//if (dummyByteStream.Length == 4)
//{
// // header complete, get message length and read rest of message
// byte[] header = dummyByteStream.ToArray();
// bytesToRead = header[0];
// bytesToRead += header[1] * 0x100;
// bytesToRead += header[2] * 0x10000;
// bytesToRead += header[3] * 0x1000000;
// bytesToRead += 5; // length + ending null
// // Signal the calling thread to continue.
//}
if (dummyByteStream.Length > 0)
{
byte[] received = dummyByteStream.ToArray();
var output = Encoding.GetEncoding(1252).GetString(received);
if ("exit".Equals(output, StringComparison.InvariantCultureIgnoreCase))
TcpListenerEndEvent.Set();
Console.WriteLine(string.Concat("Received from client: ", output));
}
} while (stream.DataAvailable && bytesToRead > dummyByteStream.Length);
// Process the connection here. (Add the client to a
// server table, read data, etc.)
//Console.WriteLine("Client connected completed");
}
catch (Exception exp)
{
Console.WriteLine(exp.StackTrace);
}
finally
{
TcpClientClosedEvent.Set();
stream.Close();
s.Close();
}
}
}
}
#---------------------------------- Client ------------------------------------------#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
namespace TcpNetwork
{
class Program
{
static void Main(string[] args)
{
DoWork();
}
private static void DoWork()
{
var str = Console.ReadLine();
for (int i = 0; i < 20; i++)
{
Thread workThread = new Thread(new ParameterizedThreadStart(ThreadWork));
workThread.Start(str);
}
Console.ReadLine();
}
private static void ThreadWork(object param)
{
try
{
String str = param as string;//Console.ReadLine();
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.1.34", 8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
using (tcpclnt)
{
NetworkStream stm = tcpclnt.GetStream();
using (stm)
{
stm.ReadTimeout = 10000;
stm.WriteTimeout = 10000;
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine(str + " Transmitting.....");
stm.Write(ba, 0, ba.Length);
//byte[] bb = new byte[100];
//int k = stm.Read(bb, 0, 100);
//for (int i = 0; i < k; i++)
// Console.Write(Convert.ToChar(bb[i]));
}
}
//str = Console.ReadLine();
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}