绝想首页

简单的聊天程序(服务端)

林仰 [其他] 2013-04-05 23:48:22 星期五 晴天 查看:81 回复:0 发消息给作者

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TcpServer
{
 ///
 /// Form1 的摘要说明。
 ///
 public class TCP : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.ListBox listBox1;
  private System.Windows.Forms.Button button2;

  private Socket server,client;
  private Hashtable clients;
  private Thread socketListen;
  private Thread clientSocket;
  private IPEndPoint newClient;
  int port=9050;
  static DateTime currentTime;
  ///
  /// 必需的设计器变量。
  ///
  private System.ComponentModel.Container components = null;

  public TCP()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  ///
  /// 清理所有正在使用的资源。
  ///
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
   
    if(clientSocket != null)
    {
     clientSocket.Abort();
    }
    if(socketListen != null)
    {
     try
     {
      socketListen.Abort();
     }
     catch(Exception)
     {
      socketListen = null;
     }
    }   

    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  
  }

  #region Windows 窗体设计器生成的代码
  ///
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///
  private void InitializeComponent()
  {
   System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(TCP));
   this.button1 = new System.Windows.Forms.Button();
   this.listBox1 = new System.Windows.Forms.ListBox();
   this.button2 = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(472, 64);
   this.button1.Name = "button1";
   this.button1.Size = new System.Drawing.Size(75, 32);
   this.button1.TabIndex = 0;
   this.button1.Text = "开启服务端";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // listBox1
   //
   this.listBox1.ItemHeight = 12;
   this.listBox1.Items.AddRange(new object[] {
                "服务器连接状态显示:"});
   this.listBox1.Location = new System.Drawing.Point(64, 32);
   this.listBox1.Name = "listBox1";
   this.listBox1.Size = new System.Drawing.Size(384, 220);
   this.listBox1.TabIndex = 1;
   this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
   //
   // button2
   //
   this.button2.Location = new System.Drawing.Point(472, 152);
   this.button2.Name = "button2";
   this.button2.Size = new System.Drawing.Size(75, 32);
   this.button2.TabIndex = 2;
   this.button2.Text = "关闭程序";
   this.button2.Click += new System.EventHandler(this.button2_Click);
   //
   // TCP
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.BackColor = System.Drawing.SystemColors.InactiveCaption;
   this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
   this.ClientSize = new System.Drawing.Size(600, 294);
   this.Controls.Add(this.button2);
   this.Controls.Add(this.listBox1);
   this.Controls.Add(this.button1);
   this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
   this.Name = "TCP";
   this.Text = "聊天程序服务端";
   this.TransparencyKey = System.Drawing.Color.Green;
   this.Load += new System.EventHandler(this.Form1_Load);
   this.ResumeLayout(false);

  }
  #endregion

  ///
  /// 应用程序的主入口点。
  ///
  [STAThread]
  static void Main()
  {
   Application.Run(new TCP());
  }

  private void Form1_Load(object sender, System.EventArgs e)
  {
   clients=new Hashtable();
  }

  private void button2_Click(object sender, System.EventArgs e)
  {
   server.Close();
   Dispose();
   this.Close();
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   IPEndPoint ipep=new IPEndPoint(IPAddress.Any,port);
   server=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
   server.Bind(ipep);
   socketListen=new Thread(new ThreadStart(StartListening));
   socketListen.Start();
  }
  private void StartListening()
  {
   server.Listen(10);
   currentTime=System.DateTime.Now;
   string hostName=Dns.GetHostName();
   listBox1.Items.Add(currentTime.ToString()+"  "+hostName+"  "+Dns.GetHostByName(hostName).AddressList[0].ToString());
   listBox1.Items.Add(currentTime.ToString()+"   welcome to the chat server!!!");
   while(true)
   {
    try
    {
     Socket client1=server.Accept();
     client=client1;
     newClient=(IPEndPoint)client1.RemoteEndPoint;
     clientSocket=new Thread(new ThreadStart(ClientStart));
     clientSocket.Start();
                   
    }
    catch(SocketException err)
    {
     MessageBox.Show("Listen erron"+err.ToString());
     break;
    }
   }
  }
  private void ClientStart()
  {
            Socket client2=client;
   bool alive=true;     //标志此线程是否存在
   bool exist=false;   //标志此客服端是否已经存在
   byte[] data;
   int recv;
   while(alive)
   {
    data=new byte[1024];
    int nameNumber;
    string name,message;
                recv=client2.Receive(data,0,data.Length,SocketFlags.None);
    string receive=Encoding.ASCII.GetString(data);
    if("exit"==receive.Substring(0,4))//退出
    {
     nameNumber=BitConverter.ToInt32(data,4);
                    name=Encoding.ASCII.GetString(data,8,nameNumber);
     clients.Remove(name);
     message=" has leave the chat server.";
     byte[] data1=new byte[1024];
     message=name+message;
     foreach(DictionaryEntry de in clients)
     {
      data=new byte[1024];
      int num=name.Length;//
      data1=Encoding.ASCII.GetBytes("exit");
      data1.CopyTo(data,0);
      data1=BitConverter.GetBytes(num);
      data1.CopyTo(data,4);
      data1=Encoding.ASCII.GetBytes(message);
      data1.CopyTo(data,4+4);
      ((Socket)de.Value).Send(data,0,data.Length,SocketFlags.None);
      
     }
     currentTime=DateTime.Now;
     message=currentTime.ToString()+"  "+message;
     listBox1.Items.Add(message);       
     break;
    }
    if("point"==receive.Substring(0,5))   //接受一对一的对话
    {
     data=new byte[1024];
     nameNumber=BitConverter.ToInt32(data,5);
     name=Encoding.ASCII.GetString(data,9,nameNumber);
     string name1;
     int num1=BitConverter.ToInt32(data,9+nameNumber);
     name1=Encoding.ASCII.GetString(data,13+nameNumber,num1);
     message=Encoding.ASCII.GetString(data,13+nameNumber+num1,recv-13-nameNumber-num1);
     Socket pointClient=client2;
     foreach(DictionaryEntry de in clients)//检查是否找到客服指定的客服机
     {
      if(de.Key.Equals(name1))
      { 
       pointClient=(Socket)de.Value;
       SendToClient(pointClient,name,message);}
     }
    }
    else
    {
     nameNumber=BitConverter.ToInt32(data,0);
     name=Encoding.ASCII.GetString(data,4,nameNumber);    
     if(!exist)   //客服机第一次进来处理的事件
     {
      exist=true;
      message=" has join the chat server.";
      byte[] data1=new byte[1024];
      foreach(DictionaryEntry de in clients)  //在客服机上显示谁登陆
      {      
       data=new byte[1024];
       data1=Encoding.ASCII.GetBytes("log");
       data1.CopyTo(data,0);
       data1=BitConverter.GetBytes(nameNumber);
       data1.CopyTo(data,3);
       data1=Encoding.ASCII.GetBytes(name);
       data1.CopyTo(data,7);
       data1=Encoding.ASCII.GetBytes(message);
       data1.CopyTo(data,3+4+nameNumber);
       ((Socket)de.Value).Send(data,0,data.Length,SocketFlags.None);
      }
      foreach(DictionaryEntry de in clients)
      {
       data=new byte[1024];
       data1=Encoding.ASCII.GetBytes("log");
       data1.CopyTo(data,0);
       data1=BitConverter.GetBytes(((string)de.Key).Length);
       data1.CopyTo(data,3);
       data1=Encoding.ASCII.GetBytes((string)de.Key);
       data1.CopyTo(data,7);
       data1=Encoding.ASCII.GetBytes(" has join the chat server.");
       data1.CopyTo(data,3+4+((string)de.Key).Length);
       client2.Send(data,0,data.Length,0);
      }
      message=name+message;
      listBox1.Items.Add(message);   //在服务器上显示客服登陆 
      clients.Add(name,client2);  
     }
     else
     {
      message=Encoding.ASCII.GetString(data,4+nameNumber,recv-4-nameNumber);
      foreach(DictionaryEntry de in clients)
      {
       SendToClient((Socket)de.Value,name,message);
      }
     }
    }
   }
   client2.Close();
  }
  private void SendToClient(Socket cl,string name,string message)
  {
   int num=name.Length;
   byte [] data=new byte[1024];
   byte [] data1=new byte[1024];
            data1=BitConverter.GetBytes(num);
   data1.CopyTo(data,0);
   data1=Encoding.ASCII.GetBytes(name);
   data1.CopyTo(data,4);
   data1=Encoding.ASCII.GetBytes(message);
   data1.CopyTo(data,4+num);
   cl.Send(data,0,data.Length,SocketFlags.None);
  }

  private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
  {
  
  }
 }
}


顶一下(32 写日记 1242187 238610
分享排行

 

 

留住已经逝去的峥嵘岁月 记住曾经绽现的万种风情 在记忆即将淡漠的时候 来把这些重新回味

Copyright (C) 2008-2014 www.juexiang.com, All Rights Reserved.

京ICP备2023001011号-3   京公网安备11010802011908号

客服QQ 1017160561 违法和不良信息举报电话 13148464312 邮箱 1017160561@qq.com