Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / .NET SDK / June 2004

Tip: Looking for answers? Try searching our database.

A simple mul-thread server .

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Amber - 03 Jun 2004 01:11 GMT
using System
using System.IO
using System.Text
using System.Threading
using System.Net.Sockets
using System.Net

namespace NetWor
{    public class Worke
   
        private Thread          thWorker
        private FileStream      logFile
        private StreamWriter    logWriter
        private NetworkStream   netStrm
        private TcpClient       tcpServer
        private string          cmd
        private byte[]          cmdbyte=new byte[1024]

        public Worker(TcpClient pserver
       
            this.tcpServer=pserver
            this.netStrm=this.tcpServer.GetStream()
       
        public void StartWork(
       
            this.thWorker=new Thread(new ThreadStart(this.DoWork))
            this.thWorker.Start()
       
        public void DoWork(
       
            int bytes=this.netStrm.Read(this.cmdbyte,0,this.cmdbyte.Length)
            cmd=Encoding.Unicode.GetString(this.cmdbyte,0,bytes)
            tr
           
                this.logFile=new FileStream("S"+cmd+".txt",FileMode.OpenOrCreate)
                this.logWriter=new StreamWriter(this.logFile)
           
            catch(Exception ex
           
                Console.WriteLine(ex.Message)
                this.tcpServer.Close()
                Thread.CurrentThread.Abort()
                return
           
            while(true
           
                bytes=this.netStrm.Read(cmdbyte,0,cmdbyte.Length)
                this.cmd=Encoding.Unicode.GetString(cmdbyte,0,bytes)
                this.logWriter.WriteLine(DateTime.Now.ToString()+": "+cmd)
                this.logWriter.Flush()
                if(cmd.ToLower().Equals("exit")
               
                    break
               
           
            this.logWriter.Close()
            this.logFile.Close()
            this.tcpServer.Close()
       
        public void StopWork(
       
            if(this.thWorker.IsAlive
           
                this.thWorker.Abort()
                this.logWriter.Close()
                this.logFile.Close()
                this.tcpServer.Close()
           
       
   

using System
using System.Collections
using System.Net.Sockets
using System.Net
using System.Threading
using System.Text
using System.IO
namespace NetWor

    class Manage
   
        public const int    listenedport=8080
        private TcpListener listener
        private Hashtable   workers=new Hashtable()
        private Thread      thListener
        private int         MaxWorkers=2
        private int         CurrentWorkers=1

        public void AcceptClients(
       
            IPHostEntry he=Dns.Resolve(Dns.GetHostName())
            if(he.AddressList.Length<1
                return
            tr
           
                IPEndPoint ep=new IPEndPoint(he.AddressList[0],Manager.listenedport )
                this.listener =new TcpListener(ep)
                this.listener.Start()
                for(;this.CurrentWorkers<=this.MaxWorkers;this.CurrentWorkers++
               
                    TcpClient client=this.listener.AcceptTcpClient()
                    Worker wker=new Worker(client)
                    this.workers.Add(this.CurrentWorkers,wker)
                    wker.StartWork()
               
             
           
            catch(Exception ex
           
                Console.WriteLine(ex.Message)
                return
           
       
        public  void StartWork(
       
            this.thListener=new Thread(new ThreadStart(this.AcceptClients))
            this.thListener.Start()
            Thread.Sleep(1000)

       
        public void StopWork(
       
            tr
           
                this.listener.Stop()
           
            catch(SocketException ex
           
                Console.WriteLine(ex.Message)
           
            tr
           
                if(this.thListener.IsAlive
               
                    this.thListener.Abort()
               
           
            catch(ThreadAbortException tex
           
                Console.WriteLine(tex.Message)
           
            catch(Exception ex
            {
                Console.WriteLine(ex.Message)
           
       
   
        [STAThread
        static void Main(string[] args
       
            Manager manager=new Manager()
            manager.StartWork()
            string cmd
            while(true
           
                cmd=Console.ReadLine()
                if(cmd.ToLower().Equals("exit")
               
                    break
               
           
            manager.StopWork()
            if(manager.workers.Count!=0
           
                IDictionaryEnumerator clients = manager.workers.GetEnumerator()
                while(clients.MoveNext()
               
                    ((Worker)clients.Value).StopWork()
               
           
       
   

using System
using System.Net
using System.Net.Sockets
using System.Text
using System.IO
namespace NetWork

    class Clien
   
        private const int intServerport=8080
        [STAThread
        static void Main(string[] args
       
            if(args.Length<1
           
                Console.WriteLine("Client should be started with a parameter")
                return
           
            string command
            byte[] cmdbyte=new byte[1024]
            TcpClient client=new TcpClient();
            NetworkStream strm;
           
            FileStream log=new FileStream(args[0]+".txt",FileMode.OpenOrCreate);
            StreamWriter sw=new StreamWriter(log);
            try
            {
                client.Connect(new IPEndPoint(IPAddress.Parse("192.168.0.1"),Client.intServerport));
                strm=client.GetStream();
                int bytes=Encoding.Unicode.GetBytes(args[0],0,args[0].Length,cmdbyte,0);
                strm.Write(cmdbyte,0,bytes);

                while(true)
                {
                    command=Console.ReadLine();
                    sw.WriteLine(DateTime.Now.ToString()+":"+command);
                    sw.Flush();
                    bytes=Encoding.Unicode.GetBytes(command,0,command.Length ,cmdbyte,0);
                    strm.Write(cmdbyte,0,bytes);
                    if(command.ToLower().Equals("exit"))
                        break;
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Close();
                sw.Close();
                log.Close();
            }
        }
    }
}

above is my code the tcplistener is listening on port 8080 in a single thread when a client connects to it the server starts a new thread to serve ,the server is work is vey simple ,just to record the client's command to an .txt file,the clients' is simple too,send a command to the server an record to a .txt file.when the server starts it's main thread keeps receieving command from the console when comes exit,it stop's the listener and it's thread and all the serve threads.Problems come here,when i typed exit in the server main thread ,the code this.listener.stop() throws a exception .I know the thread listener listenes is suspend because i a call the this.listener.acceptTcpClient function .But how can achieve the goal to control the behavior the listener ,I want it to stop ,it stops regardless it is block in it's thread
Amber - 04 Jun 2004 05:51 GMT
Anybody help me?
Chad Z. Hower aka Kudzu - 04 Jun 2004 13:53 GMT
> above is my code the tcplistener is listening on port 8080 in a single
> thread when a client connects to it the server starts a new thread to
> serve ,the server is work is vey simple ,just to record the client's
> command to an .txt file,the clients' is simple too,send a command to the

You might try Indy - it does all this low level work for you and its free.

www.indyproject.org

There is a server demo in C# here:
www.atozed.com/indy/

--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
     "Programming is an art form that fights back"

Get your ASP.NET in gear with IntraWeb!
 http://www.atozed.com/IntraWeb/
Amber - 06 Jun 2004 11:16 GMT
I am just a student ,and I want to write the code myself ,would anyone mind reading my code
Todd Bright - 16 Jun 2004 22:37 GMT
You've probably got this one figured out by now, but here goes.  I think what you're wanting is a way to tell the listening thread(s) to stop listening from within the main thread.  One good way to do this is to implement a class with a static property that all threads look at.  Simply set the property to indicate that all threads should exit.  In the worker threads read the static property to see if they should exit (probably in an idle loop or during processing).

> using System;
> using System.IO;
[quoted text clipped - 231 lines]
>
> above is my code the tcplistener is listening on port 8080 in a single thread when a client connects to it the server starts a new thread to serve ,the server is work is vey simple ,just to record the client's command to an .txt file,the clients' is simple too,send a command to the server an record to a .txt file.when the server starts it's main thread keeps receieving command from the console when comes exit,it stop's the listener and it's thread and all the serve threads.Problems come here,when i typed exit in the server main thread ,the code this.listener.stop() throws a exception .I know the thread listener listenes is suspend because i a call the this.listener.acceptTcpClient function .But how can achieve the goal to control the behavior the listener ,I want it to stop ,it stops regardless it is block in it's thread.

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.