CSDN技术中心 简单的多人聊天(C#_Socket)

来源:互联网 发布:中欣卡可以在淘宝用吗 编辑:程序博客网 时间:2024/05/02 00:00
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace Chat_Server
{
 
/// <summary>
 
/// Form1 的摘要说明。
 
/// </summary>

 public class Form1 : System.Windows.Forms.Form
 
{
  
/// <summary>
  
/// 必需的设计器变量。
  
/// </summary>

  private System.ComponentModel.Container components = null;

  
static int listenport=6666;
  Socket clientsocket;
  
private System.Windows.Forms.ListBox lbClients;
  ArrayList clients;
  
private System.Windows.Forms.Button button1;
  Thread clientservice;
  
private System.Windows.Forms.Label label1;
  Thread threadListen;

  
public Form1()
  
{
   
   InitializeComponent();

  }


  
/// <summary>
  
/// 清理所有正在使用的资源。
  
/// </summary>

  protected override void Dispose( bool disposing )
  
{
   
if( disposing )
   
{
    
    
if(clientservice != null)
    
{
     clientservice.Abort();
    }

    
if(threadListen != null)
    
{
     
try
     
{
      threadListen.Abort();
     }

     
catch(Exception ex)
     
{
      threadListen 
= null;
     }

    }
    

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

   }

   
base.Dispose( disposing );
   
  }


  
Windows 窗体设计器生成的代码

  
/// <summary>
  
/// 应用程序的主入口点。
  
/// </summary>

  [STAThread]
  
static void Main() 
  
{
   Application.Run(
new Form1());
  }


  
private void StartListening() 
  

    TcpListener listener 
= new TcpListener(listenport);
    listener.Start();
   label1.Text 
= "listening....";
   
while (true
   
{
    
try
    
{
    
     Socket s 
= listener.AcceptSocket(); 
     clientsocket 
= s; 
     clientservice 
= new Thread(new ThreadStart(ServiceClient)); 
     clientservice.Start(); 
    }

    
catch(Exception ex)
    
{
     MessageBox.Show(
"listening Error: "+ex.Message);
    }

   }
   
  }

  
private void ServiceClient() 
  

   Socket client 
= clientsocket; 
   
bool keepalive = true


   
while (keepalive) 
   

    Byte[] buffer 
= new Byte[1024]; 
    
int bufLen = 0;
    
try
    
{
     bufLen 
= client.Available ;
     
     client.Receive(buffer,
0,bufLen,SocketFlags.None); 
     
if(bufLen==0)
      
continue;    
    }

    
catch(Exception ex)
    
{
     MessageBox.Show(
"Receive Error:"+ex.Message);
     
return;
    }

    
    
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0,bufLen); 

    
string[] tokens = clientcommand.Split(new Char[]{'|'}); 
    Console.WriteLine(clientcommand); 

    
if (tokens[0== "CONN"
    

     
for(int n=0; n<clients.Count;n++)
     

      Client cl 
= (Client)clients[n]; 
      SendToClient(cl, 
"JOIN|" + tokens[1]); 
     }

     EndPoint ep 
= client.RemoteEndPoint; 
     Client c 
= new Client(tokens[1], ep, clientservice, client); 
     
     
string message = "LIST|" + GetChatterList() +" "
     SendToClient(c, message); 

     clients.Add(c); 


     lbClients.Items.Add(c); 


    }

    
if (tokens[0== "CHAT"
    

     
for(int n=0; n<clients.Count;n++)
     

      Client cl 
= (Client)clients[n]; 
      SendToClient(cl, clientcommand); 
     }

    }

    
if (tokens[0== "PRIV"
    

     
string destclient = tokens[3]; 
     
for(int n=0; n<clients.Count;n++)
     

      Client cl 
= (Client)clients[n]; 
      
if(cl.Name.CompareTo(tokens[3]) == 0
       SendToClient(cl, clientcommand); 
      
if(cl.Name.CompareTo(tokens[1]) == 0
       SendToClient(cl, clientcommand); 
     }
 
    }
 
    
if (tokens[0== "GONE"
    

     
int remove = 0
     
bool found = false
     
int c = clients.Count; 
     
for(int n=0; n<clients.Count;n++)
     

      Client cl 
= (Client)clients[n]; 
      SendToClient(cl, clientcommand); 
      
if(cl.Name.CompareTo(tokens[1]) == 0
      

       remove 
= n; 
       found 
= true
       lbClients.Items.Remove(cl); 
      }
 
     }
 
     
if(found) 
      clients.RemoveAt(remove); 
     client.Close(); 
     keepalive 
= false
    }
 
   }
 
  }


  
private string GetChatterList()
  
{
   
string result = "";

   
for(int i=0;i<clients.Count;i++)
   
{
    result 
+= ((Client)clients[i]).Name+"|";
   }

   
return result;

  }


  
private void SendToClient(Client cl,string clientCommand)
  
{
   Byte[] message 
= System.Text.Encoding.ASCII.GetBytes(clientCommand);
   Socket s 
= cl.Sock;
   
if(s.Connected)
   
{
    s.Send(message,message.Length,
0);
   }

  }


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


  
private void button1_Click(object sender, System.EventArgs e)
  
{
   threadListen 
= new Thread(new ThreadStart(StartListening));
   threadListen.Start();  
  }
 
 }
 
}






/***************************** client类 ********************/

/************************** 放于 chatServer 项目中 *********/

using System; 
using System.Threading; 

namespace Chat_Server 

 
using System.Net.Sockets; 
 
using System.Net; 

 
/// 
 
/// Client 的摘要说明。 
 
/// 

 public class Client 
 

  
private Thread clthread; 
  
private EndPoint endpoint; 
  
private string name; 
  
private Socket sock; 

  
public Client(string _name, EndPoint _endpoint, Thread _thread, Socket _sock) 
  

   
// TODO: 在此处添加构造函数逻辑 
   clthread = _thread; 
   endpoint 
= _endpoint; 
   name 
= _name; 
   sock 
= _sock; 
  }
 

  
public override string ToString() 
  

   
return endpoint.ToString()+ " : " + name; 
  }
 

  
public Thread CLThread 
  

   
get{return clthread;} 
   
set{clthread = value;} 
  }
 

  
public EndPoint Host 
  

   
get{return endpoint;} 
   
set{endpoint = value;} 
  }
 

  
public string Name 
  

   
get{return name;} 
   
set{name = value;} 
  }
 

  
public Socket Sock 
  

   
get{return sock;} 
   
set{sock = value;} 
  }
 
 }
 
}
 

/***************************** chatClient ************************************/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Chat_Client
{
 
/// <summary>
 
/// Form1 的摘要说明。
 
/// </summary>

 public class Form1 : System.Windows.Forms.Form
 
{
  
private System.Windows.Forms.CheckBox checkBox1;
  
private System.Windows.Forms.StatusBar statusBar1;

  NetworkStream ns;
  StreamReader sr;
  TcpClient clientsocket;
  
bool connected;
  Thread receive;
  
string serveraddress = "219.228.231.85";
  
int serverport = 6666;

  
private System.Windows.Forms.RichTextBox rtbChatIn;
  
private System.Windows.Forms.ListBox lbChatters;
  
private System.Windows.Forms.TextBox ChatOut;
  
private System.Windows.Forms.Button btnDisconnect;
  
private System.Windows.Forms.Button btnSend;
  
private System.Windows.Forms.TextBox clientName;

  
string clientname;
  
private System.Windows.Forms.Button btnConnect;

  
private System.ComponentModel.Container components = null;

  
public Form1()
  
{
   
   InitializeComponent();

  }


  
/// <summary>
  
/// 清理所有正在使用的资源。
  
/// </summary>

  protected override void Dispose( bool disposing )
  
{
   
if( disposing )
   
{
    
if(receive != null)
    
{
     QuitChat();
    }

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

   }

   
base.Dispose( disposing );
  }


  
Windows 窗体设计器生成的代码

  
/// <summary>
  
/// 应用程序的主入口点。
  
/// </summary>

  [STAThread]
  
static void Main() 
  
{
   Application.Run(
new Form1());
  }


  
private void EstablishConnection() 
  

   statusBar1.Text 
= "正在连接到服务器"
   
   
try 
   

    clientsocket 
= new TcpClient(serveraddress,serverport); 
    ns 
= clientsocket.GetStream(); 
    sr 
= new StreamReader(ns); 
    connected 
= true
   
   }
 
   
catch (Exception) 
   

    MessageBox.Show(
"不能连接到服务器!","错误"
     MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
    statusBar1.Text 
= "已断开连接"
   }
 
  }
 

  
private void RegisterWithServer() 
  

   lbChatters.Items.Clear();

   clientname 
= clientName.Text;
   
try 
   

    
string command = "CONN|" + clientname; //+" "; 
    Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray()); 
    ns.Write(outbytes,
0,outbytes.Length); 


    
string serverresponse = sr.ReadLine(); 
    serverresponse.Trim(); 
    
string[] tokens = serverresponse.Split('|'); 
    
if(tokens[0== "LIST"
    

     statusBar1.Text 
= "已连接"
     btnDisconnect.Enabled 
= true
    }

    
if(tokens[1!= "")
    
{
     
for(int n=1; n<tokens.Length;n++)
      lbChatters.Items.Add(tokens[n].Trim(
new char[]{' ',' '})); 
    }

    
this.Text = clientname + ":已连接到服务器";    

   }
 
   
catch (Exception ex) 
   

    MessageBox.Show(
"注册时发生错误!"+ex.Message,"错误"
     MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
    connected 
= false;
   }
 
  }
 

  
private void ReceiveChat() 
  

   
bool keepalive = true
   
while (keepalive) 
   

    
try 
    

     Byte[] buffer 
= new Byte[1024];  // 2048???
     ns.Read(buffer,0,buffer.Length); 
     
string chatter = System.Text.Encoding.ASCII.GetString(buffer); 
     
string[] tokens = chatter.Split(new Char[]{'|'}); 

     
if (tokens[0== "CHAT"
     

      rtbChatIn.AppendText(tokens[
1]); 
//      if(logging) 
//       logwriter.WriteLine(tokens[1]); 
     }
 
     
if (tokens[0== "PRIV"
     

      rtbChatIn.AppendText(
"Private from "); 
      rtbChatIn.AppendText(tokens[
1].Trim() ); 
      rtbChatIn.AppendText(tokens[
2+ " "); 
//      if(logging) 
//      { 
//       logwriter.Write("Private from "); 
//       logwriter.Write(tokens[1].Trim() ); 
//       logwriter.WriteLine(tokens[2] + " "); 
//      } 
     }
 
     
if (tokens[0== "JOIN"
     

      rtbChatIn.AppendText(tokens[
1].Trim() ); 
      rtbChatIn.AppendText(
" has joined the Chat "); 
//      if(logging) 
//      { 
//       logwriter.WriteLine(tokens[1]+" has joined the Chat"); 
//      } 
      string newguy = tokens[1].Trim(new char[]{' ',' '}); 
      lbChatters.Items.Add(newguy); 
     }
 
     
if (tokens[0== "GONE"
     

      rtbChatIn.AppendText(tokens[
1].Trim() ); 
      rtbChatIn.AppendText(
" has left the Chat "); 
//      if(logging) 
//      { 
//       logwriter.WriteLine(tokens[1]+" has left the Chat"); 
//      } 
      lbChatters.Items.Remove(tokens[1].Trim(new char[]{' ',' '})); 
     }
 
     
if (tokens[0== "QUIT"
     

      ns.Close(); 
      clientsocket.Close(); 
      keepalive 
= false
      statusBar1.Text 
= "服务器端已停止"
      connected
= false
      btnSend.Enabled 
= false
      btnDisconnect.Enabled 
= false
     }
 
    }
 
    
catch(Exception){} 
   }
 
  }
 

  
private void QuitChat() 
  

   
if(connected) 
   

    
try 
    

     
string command = "GONE|" + clientname; 
     Byte[] outbytes 
= System.Text.Encoding.ASCII.GetBytes(command.ToCharArray()); 
     ns.Write(outbytes,
0,outbytes.Length); 
     clientsocket.Close(); 
    }
 
    
catch(Exception ex) 
    

     MessageBox.Show(ex.Message);
    }
 
   }
 
//   if(logging) 
//    logwriter.Close(); 
   if(receive != null && receive.IsAlive) 
    receive.Abort(); 
   
this.Text = "客户端"
   
   connected 
= false;

  }


  
private void btnSend_Click(object sender, System.EventArgs e)
  
{
   
if(connected) 
   

    
try 
    

     
string command = "CHAT|" + clientname+""+ChatOut.Text+" "
     Byte[] outbytes 
= System.Text.Encoding.ASCII.GetBytes(command.ToCharArray()); 
     ns.Write(outbytes,
0,outbytes.Length); 
     
//clientsocket.Close(); 
    }
 
    
catch(Exception ex) 
    

     MessageBox.Show(ex.Message);
    }
 
   }
 
  }


  
private void btnConnect_Click(object sender, System.EventArgs e)
  
{
   EstablishConnection();
   RegisterWithServer();
   
if(connected)
   
{   
    receive 
= new Thread(new ThreadStart(ReceiveChat));
    receive.Start();
   }

  }


  
private void btnDisconnect_Click(object sender, System.EventArgs e)
  
{
   QuitChat();
  }

 }

}