Latest Snippet Version: 0.1
Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Threading;
/*
Copyright (c) 2002, Stefan Muenzel (smuenzel@users.sourceforge.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclawing.
-Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclawing in the documentation and/or other materials provided with the distribution.
-Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, INCLUDING, but not limited, the implied warranties of merchantability and fitness for a special purpose are disclaimed. in no event shall the copyright owner or contributors be liable for any direct, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, or consequential damages (INCLUDING, but not limited, procurement of substitute goods or services; loss of use, DATA, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
*/
Namespace telnetchatd
{
Public class Utility
{
Public static readonly byte [] Backspace = {0x08 };
Public static readonly byte [] CrLf = {0x0D, 0x0A };
Private Utility (){}
Public static byte [] StrToByte (string str)
{
Char [] car = str. ToCharArray ();
Byte [] bar = new byte [car. Length];
Int I = 0;
Foreach (char c in car)
{
Bar [I] = (byte) c;
I ++;
}
Return bar;
}
Public static void SendString (Socket sock, string s)
{
If (sock = null)
Throw new System. NullReferenceException ("(SendString) No Socket to Send ");
Sock. Send (StrToByte (s ));
}
// Write to local console
Public static void prLocal (string str)
{
PrLog ("<Daemon>" + str );
Console. WriteLine ("<Daemon>" + str );
}
// Write to log with timestamp
Public static void prLog (string str)
{
System. DateTime mt = System. DateTime. Now;
Stream stream = File. Open ("log. log", FileMode. Append, FileAccess. Write, FileShare. ReadWrite );
StreamWriter fstream = new StreamWriter (stream );
Fstream. WriteLine ("$" + mt. ToLongTimeString () + "$" + str );
Fstream. Close ();
Stream. Close ();
}
}
Public class ChatD
{
Static ChatD mInstance;
Private IPEndPoint mPort = new IPEndPoint (IP address. Any, 12345 );
Private System. Collections. ArrayList mConnected;
Private Socket mSockListen;
/* Class used to represent one client, all clients are saved in mConnected, and delete themselves
* When the remote side disconnects
*/
Public class cClient
{
String WELCOME = ". NET Telnet Chat Service \ r \ n" +
"To talk just type and press <ENTER>. \ r \ n" +
"If you wowould like to change your client name, type '$ 'followed by the new name. \ r \ n" +
"Please turn local echo off. \ r \ n ";
// Private string Send;
Private Thread mThread; // The thread this client runs in
Internal string UserName;
Internal string Current;
Internal Socket Sock;
Internal int BackSpaceCount; // how to configure backspace the user has accumulated
~ CClient () // Never called, since RequestFinalize () doesn't exist
{
Utility. prLog ("~ "+ This. UserName +" destroyed .");
}
Public cClient ()
{
This. Sock = null;
This. Current = "";
This. BackSpaceCount = 0;
System. GC. ReRegisterForFinalize (this); // does nothing at all
}
Public void DoInNewThread ()
{
ThreadStart ts = new ThreadStart (this. ThreadMethod );
MThread = new Thread (ts );
MThread. Start ();
}
Private void ThreadMethod ()
{
Byte [] buffer = new byte [24];
Utility. SendString (this. Sock, WELCOME );
Int crec = 0; // length of incoming data
While (true)
{
// Check if I'm supposed to be dead:
If (! ChatD. mInstance. mConnected. Contains (this ))
{
Break;
}
// Incoming Loop
Try
{
If (this. Sock. Poll (100, SelectMode. SelectRead) // Poll the socket for incoming data
{
If (crec = this. Sock. Receive (buffer) = 0) // if your Ed data = 0, the remote side closed
{
Sock. Shutdown (SocketShutdown. Both );
Sock. Close ();
Break;
}
Else
{
If (System. Collections. IList) buffer). Contains (byte) '\ n') |
(System. Collections. IList) buffer). Contains (byte) '\ R '))
{
// When a newline is contained, emit the string
If (Current. Length> 0)
{
Sock. Send (Utility. CrLf );
If (Current [0] = '$') // name change
{
ChatD. mInstance. BroadCast (null, ">" + this. UserName +
"<Changed name to" + Current. Substring (1), true );
This. UserName = Current. Substring (1 );
}
Else
{
// Emit the string to all other clients
ChatD. mInstance. BroadCast (this, Current );
}
Current = "";
}
}
Else
{
If (! Char. IsControl (char) buffer [0]) &! (Buffer [0] = 0x08 ))
{
// Add the incoming characters to the buffer
This. Sock. Send (buffer );
For (int I = 0; I <crec; I ++)
{
This. Current + = (char) buffer [I];
// This. Current = this. Current. Remove (this. Current. Length-(24-crec + 1), (24-crec + 1 ));
If (this. BackSpaceCount> 0) this. BackSpaceCount --;
}
}
Else if (buffer [0] = 0x08 & Current. Length> 0)
{
// Process backspaces
Try
{
This. Current = this. Current. Remove (this. Current. Length-1, 1 );
This. BackSpaceCount ++;
This. Sock. Send (buffer );
}
Catch (System. ArgumentOutOfRangeException ex)
{
}
}
}
// Make new buffer
Buffer = new byte [24];
}
}
}
Catch (System. Net. Sockets. SocketException sx)
{
Utility. prLocal ("Error handling from client" + this. Sock. RemoteEndPoint. ToString () + "("
+ This. UserName + ")");
Utility. prLocal ("\ tError:" + sex. ErrorCode. ToString () + ", Native :"
+ Sx. NativeErrorCode. ToString () + "," + sx. Message );
Break;
}
}
// Destruction:
ChatD. mInstance. mConnected. Remove (this );
ChatD. mInstance. BroadCast (null, this. UserName + "has left the server .");
}
};
[STAThread]
Static void Main (string [] args)
{
Utility. prLocal ("Initializing ...");
ChatD baseDaemon = new ChatD ();
}
Public ChatD ()
{
ChatD. mInstance = this;
MConnected = new System. Collections. ArrayList (21 );
MSockListen = new Socket (AddressFamily. InterNetwork,
SocketType. Stream, ProtocolType. Tcp); // create the listening socket
Utility. prLocal ("Initializing completed .");
This. Commence ();
}
~ ChatD ()
{
Utility. prLocal ("Shuting down ...");
}
Public void Commence ()
{
MSockListen. Bind (mPort); // Bind and listen
DoListen ();
}
Public void DoListen ()
{
CClient tempclient = new cClient ();
Int tempn;
MSockListen. Listen (2048 );
While (true ){
If (mSockListen. Poll (10000, SelectMode. SelectRead) // Poll the socket and create clients on incoming connections
{
Utility. prLocal ("Incoming connection ...");
Tempclient. Sock = mSockListen. Accept ();
Tempclient. UserName = "New User ";
Tempclient. Current = "";
Utility. prLocal ("\ t... from" + tempclient. Sock. RemoteEndPoint. ToString ());
This. BroadCast (null, ">" + tempclient. UserName + "<joined the server .");
Tempn = mConnected. Add (tempclient );
(CClient) mConnected [tempn]). DoInNewThread ();
Tempclient = new cClient ();
}
}
}
Public void BroadCast (cClient broadcaster, string s)
{
This. BroadCast (broadcaster, s, false );
}
Public void BroadCast (cClient broadcaster, string s, bool ne)
{
String tstr;
If (broadcaster = null) // Daemon
{
Tstr = s + "\ r \ n ";
}
Else
{
Tstr = "<" + broadcaster. UserName + ">" + s + "\ r \ n ";
}
Byte [] bar = Utility. StrToByte (tstr );
// Send to every client:
Foreach (object ob in this. mConnected)
{
Try
{
// Send "\ r \ n" to clients that have typed something
If (cClient) ob). Current. Length> 2) & (ob! = Broadcaster) (cClient) ob). Sock. Send (Utility. CrLf );
(CClient) ob). Sock. Send (bar); // Send String
// Echo their current string and backspaces back:
If (! Ne) if (ob! = Broadcaster) (cClient) ob). Sock. Send (Utility. StrToByte (cClient) ob). Current ));
For (int I = 0; I <(cClient) ob). BackSpaceCount; I ++)
(CClient) ob). Sock. Send (Utility. Backspace );
}
Catch (System. Net. Sockets. SocketException sx)
{
Utility. prLocal ("Error sending to client" + (cClient) ob). Sock. RemoteEndPoint. ToString () + "("
+ (CClient) ob). UserName + ")");
Utility. prLocal ("\ tError:" + sx. ErrorCode. ToString () + ", Native:" + sx. NativeErrorCode. ToString ()
+ "," + Sex. Message );
This. mConnected. Remove (ob );
}
}
Tstr = tstr. Substring (0, tstr. Length-2) + '\ n'; // make fit for writing to file
Utility. prLog (tstr );
Console. Write (tstr );
}
}
}