[转帖]我写的SOCKET SERVER 例子

原文地址:http://www.cnblogs.com/3188/archive/2004/06/14/15477.html

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
 
namespace Synjones.NET.Sockets
{
     
delegate void NewConnection(string IP);
     
delegate void LostConnection(string ip);
     
delegate void TranseData(byte[] data);
 
     
public class SocketServerThread
     
{
         NewConnection newc;
         LostConnection lcwc;
         TranseData td;
 
         
static SocketServerThread instance;
         System.Net.Sockets.TcpListener socketListener,threadListener;
         
public ArrayList alConnections = null;// 存在的连接
         public ArrayList alConnectionThread = null;// 连接线程
         Thread listenerThread,connectionThread;// 线程:监听线程和连接线程(每个连接有一个)
 
         
bool _Started;
         
public bool Started{
              
get{return this._Started;}
         }

 
         SocketServerThread()
         
{
              socketListener 
= null;
         }

 
         
void listen()
         
{
              
if(!Started)
              
{
                   
try
                   
{
                       IPEndPoint ipep 
= new IPEndPoint(IPAddress.Any,8005);
                       socketListener 
= new TcpListener(ipep);
         
                       socketListener.Start();
                       
this._Started = true;
                       
while(this.listenerThread.ThreadState == System.Threading.ThreadState.Running)
                       
{
                            
while(socketListener.Pending())      //是否存在挂起的连接
                            {
                                 threadListener 
= socketListener;
                                 connectionThread 
= new Thread(new ThreadStart(handleConnections));
                                 connectionThread.Start();                          
 
                                 
lock(alConnectionThread)
                                 
{
                                     alConnectionThread.Add(connectionThread);      
                                 }

 
                                 Thread.Sleep(
100);
                            }

                            Thread.Sleep(
100);
                       }
    
                   }

                   
catch(Exception ex)
                   
{
                       Trace.WriteLine(
"发生错误:" + ex.ToString(),DateTime.Now.ToString());
                   }

              }

         }

 
         
void handleConnections()    //处理socket连接
         {
              
int recv;
              
byte[] data = new byte[1024];
              Socket client 
= threadListener.AcceptSocket();
              
if(client.Connected)
              
{
                   
lock(alConnections)
                   
{
                       alConnections.Add(client);
                   }

                   Debug.WriteLine(
"\r\r\rNew Connection connected from " + client.RemoteEndPoint +"\t" + System.DateTime.Now.ToLongTimeString());
 
                   
string fromIp = ((IPEndPoint)client.RemoteEndPoint).Address.ToString();
 
                   newc(fromIp);
 
                   
while(true)
                   
{        
                       
try
                       
{
                            
//data = new byte[包头大小];
                            data = new byte[1];
                            recv 
= client.Receive(data,0,data.Length,SocketFlags.None);
                            
if (recv == 0
                            
{
                                 Debug.WriteLine(
"Connection Closed by Client:" + client.RemoteEndPoint);//客户端断开了连接
                                 break;        
                            }
                  
                            
//处理包头数据(data);
                            Debug.WriteLine(data[0].ToString("X2"));
                            client.Send(data);
 
                            
//data = new byte[包头中定义的包体大小];
                            
//recv = client.Receive(data,0,data.Length,SocketFlags.None);
                            
//if (recv == 0) 
                            
//{
                            
//   Debug.WriteLine("Connection Closed by Client:" + client.RemoteEndPoint);//客户端断开了连接
                            
//   break;        
                            
//}
                            
//处理包体数据(data);  
 
                            Thread.Sleep(
200);         //循环等待时间,确定多长时间读一次Socket缓冲区
                       }

                       
catch(Exception ex)
                       
{
                            Debug.WriteLine(ex.ToString());
                            
break;
                       }

                   }

                   
lock(alConnections)
                   
{
                       alConnections.Remove(client);                      
                   }

                   lcwc(fromIp);
                   client.Close();                
              }

         }

 
         
public void Start(SocketServerAPP.FormSocketServerTest form)
         
{
              
if(!this.Started)
              
{
                   newc 
= new NewConnection(form.NewConnection);
                   lcwc 
= new LostConnection(form.LostConnection);
 
 
                   Debug.Listeners.Add(
new ConsoleListener());
                   Debug.WriteLine(
"监听服务线程开始.",DateTime.Now.ToString());
                   alConnections 
= new ArrayList();
                   alConnectionThread 
= new ArrayList();
                   listenerThread 
= new Thread(new ThreadStart(listen));//创建监听线程
                   listenerThread.Start();
              }

         }

 
         
public void Stop()
         
{
              
if(this.Started)
              
{
                   
this._Started = false;
                   
//Disconnect socket client connection
                   for (int i = 0;i < alConnections.Count;i++)
                   
{
                       Trace.WriteLine(
"关闭连接:" + ((Socket)alConnections[i]).RemoteEndPoint.ToString(),DateTime.Now.ToString());
                       ((Socket)alConnections[i]).Close();
                   }

                   
//Stop socket client connection thread
                   for (int i = 0;i < alConnectionThread.Count;i++)
                   
{                      
                       Trace.WriteLine(
"关闭线程:" + ((Thread)alConnectionThread[i]).Name,DateTime.Now.ToString());
                       ((Thread)alConnectionThread[i]).Abort();
                   }

                   
//Stop socket server listener
                   socketListener.Stop(); 
                   
//Stop socket server thread
                   listenerThread.Abort();
                   alConnectionThread.Clear();
                   alConnections.Clear();
                   Debug.WriteLine(
"监听服务线程终止.",DateTime.Now.ToString());
              }

         }

 
 
         
//signleten pattern
         public static SocketServerThread GetInstance(){
              
if(instance == null)
                   instance 
= new SocketServerThread();
              
return instance;
         }

     }

     
 
     
public class ConsoleListener :TraceListener //将调试信息定向到控制台
     {
         
public override void WriteLine(string message){
              Console.WriteLine(message);
         }

 
         
public override void Write(string message){
              Console.Write(message);
         }

     }

}

posted on 2004-11-21 09:00  Ja  阅读(1254)  评论(0编辑  收藏  举报

导航