简单的多人聊天(C#.Socket).

/********************************8ChatServer:*************************************************/

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
{
///

1<summary>   
2/// Form1 的摘要说明。   
3/// </summary>

public class Form1 : System.Windows.Forms.Form
{
///

1<summary>   
2/// 必需的设计器变量。   
3/// </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();

}

///

1<summary>   
2/// 清理所有正在使用的资源。   
3/// </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 );

}

#region Windows 窗体设计器生成的代码
///

1<summary>   
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改   
3/// 此方法的内容。   
4/// </summary>

private void InitializeComponent()
{
this.lbClients = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lbClients
//
this.lbClients.ItemHeight = 12;
this.lbClients.Location = new System.Drawing.Point(16, 24);
this.lbClients.Name = "lbClients";
this.lbClients.Size = new System.Drawing.Size(184, 268);
this.lbClients.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(272, 56);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(240, 136);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(120, 32);
this.label1.TabIndex = 2;
this.label1.Text = "label1";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(368, 309);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.lbClients);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

///

1<summary>   
2/// 应用程序的主入口点。   
3/// </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

  1<clients.count;n++) "="" "join|"="" (tokens[0]="GONE" )="" *********="" ********************="" **************************="" *****************************="" ************************************="" +="" +"\r\n";="" :="" ;="" <summary="" _endpoint,="" _name,="" _sock)="" _thread,="" arraylist();="" bool="" button1_click(object="" byte[]="" c="clients.Count;" chat_client="" chat_server="" chatclient="" chatserver="" cl="(Client)clients[n];" cl,string="" class="" client="" client(string="" client(tokens[1],="" client);="" client.close();="" clientcommand)="" clientcommand);="" clients="new" clients.add(c);="" clients.removeat(remove);="" clientservice,="" client类="" clthread="" clthread;="" clthread;}="" destclient="tokens[3];" e)="" endpoint="" endpoint.tostring()+="" endpoint;="" endpoint;}="" ep="client.RemoteEndPoint;" ep,="" for(int="" form1_load(object="" found="true;" getchatterlist()="" get{return="" host="" i="0;i&lt;clients.Count;i++)" if="" if(cl.name.compareto(tokens[1])="0)" if(cl.name.compareto(tokens[3])="0)" if(found)="" if(s.connected)="" int="" keepalive="false;" lbclients.items.add(c);="" lbclients.items.remove(cl);="" message="System.Text.Encoding.ASCII.GetBytes(clientCommand);" message);="" n="0;" n<clients.count;n++)="" name="" name;="" name;}="" namespace="" override="" private="" public="" remove="n;" result="" result;="" return="" s="cl.Sock;" s.send(message,message.length,0);="" sender,="" sendtoclient(c,="" sendtoclient(cl,="" sendtoclient(client="" set{clthread="value;}" set{endpoint="value;}" set{name="value;}" set{sock="value;}" sock="" sock;="" sock;}="" socket="" string="" system.collections;="" system.componentmodel;="" system.data;="" system.drawing;="" system.eventargs="" system.io;="" system.net.sockets;="" system.net;="" system.threading;="" system.windows.forms;="" system;="" thread="" thread(new="" threadlisten="new" threadlisten.start();="" threadstart(startlistening));="" todo:="" tokens[1]);="" tostring()="" using="" void="" {="" }="" 在此处添加构造函数逻辑="" 放于="" 的摘要说明。="" 项目中="">   
  2/// Form1 的摘要说明。   
  3///    
  4public class Form1 : System.Windows.Forms.Form   
  5{   
  6private System.Windows.Forms.CheckBox checkBox1;   
  7private System.Windows.Forms.StatusBar statusBar1; 
  8
  9NetworkStream ns;   
 10StreamReader sr;   
 11TcpClient clientsocket;   
 12bool connected;   
 13Thread receive;   
 14string serveraddress = "219.228.231.85";   
 15int serverport = 6666; 
 16
 17private System.Windows.Forms.RichTextBox rtbChatIn;   
 18private System.Windows.Forms.ListBox lbChatters;   
 19private System.Windows.Forms.TextBox ChatOut;   
 20private System.Windows.Forms.Button btnDisconnect;   
 21private System.Windows.Forms.Button btnSend;   
 22private System.Windows.Forms.TextBox clientName; 
 23
 24string clientname;   
 25private System.Windows.Forms.Button btnConnect; 
 26
 27private System.ComponentModel.Container components = null; 
 28
 29public Form1()   
 30{   
 31  
 32InitializeComponent(); 
 33
 34} 
 35
 36/// <summary>   
 37/// 清理所有正在使用的资源。   
 38/// </summary>   
 39protected override void Dispose( bool disposing )   
 40{   
 41if( disposing )   
 42{   
 43if(receive != null)   
 44{   
 45QuitChat();   
 46}   
 47if (components != null)   
 48{   
 49components.Dispose();   
 50}   
 51}   
 52base.Dispose( disposing );   
 53} 
 54
 55#region Windows 窗体设计器生成的代码   
 56/// <summary>   
 57/// 设计器支持所需的方法 - 不要使用代码编辑器修改   
 58/// 此方法的内容。   
 59/// </summary>   
 60private void InitializeComponent()   
 61{   
 62this.lbChatters = new System.Windows.Forms.ListBox();   
 63this.rtbChatIn = new System.Windows.Forms.RichTextBox();   
 64this.checkBox1 = new System.Windows.Forms.CheckBox();   
 65this.ChatOut = new System.Windows.Forms.TextBox();   
 66this.btnSend = new System.Windows.Forms.Button();   
 67this.statusBar1 = new System.Windows.Forms.StatusBar();   
 68this.btnDisconnect = new System.Windows.Forms.Button();   
 69this.clientName = new System.Windows.Forms.TextBox();   
 70this.btnConnect = new System.Windows.Forms.Button();   
 71this.SuspendLayout();   
 72//   
 73// lbChatters   
 74//   
 75this.lbChatters.ItemHeight = 12;   
 76this.lbChatters.Location = new System.Drawing.Point(32, 40);   
 77this.lbChatters.Name = "lbChatters";   
 78this.lbChatters.Size = new System.Drawing.Size(112, 172);   
 79this.lbChatters.TabIndex = 0;   
 80//   
 81// rtbChatIn   
 82//   
 83this.rtbChatIn.Location = new System.Drawing.Point(160, 40);   
 84this.rtbChatIn.Name = "rtbChatIn";   
 85this.rtbChatIn.Size = new System.Drawing.Size(208, 176);   
 86this.rtbChatIn.TabIndex = 2;   
 87this.rtbChatIn.Text = "";   
 88//   
 89// checkBox1   
 90//   
 91this.checkBox1.Location = new System.Drawing.Point(16, 248);   
 92this.checkBox1.Name = "checkBox1";   
 93this.checkBox1.TabIndex = 3;   
 94this.checkBox1.Text = "checkBox1";   
 95//   
 96// ChatOut   
 97//   
 98this.ChatOut.Location = new System.Drawing.Point(136, 248);   
 99this.ChatOut.Name = "ChatOut";   
100this.ChatOut.Size = new System.Drawing.Size(136, 21);   
101this.ChatOut.TabIndex = 4;   
102this.ChatOut.Text = "message";   
103//   
104// btnSend   
105//   
106this.btnSend.Location = new System.Drawing.Point(336, 248);   
107this.btnSend.Name = "btnSend";   
108this.btnSend.TabIndex = 5;   
109this.btnSend.Text = "send";   
110this.btnSend.Click += new System.EventHandler(this.btnSend_Click);   
111//   
112// statusBar1   
113//   
114this.statusBar1.Location = new System.Drawing.Point(0, 287);   
115this.statusBar1.Name = "statusBar1";   
116this.statusBar1.Size = new System.Drawing.Size(464, 22);   
117this.statusBar1.TabIndex = 6;   
118this.statusBar1.Text = "statusBar1";   
119//   
120// btnDisconnect   
121//   
122this.btnDisconnect.Enabled = false;   
123this.btnDisconnect.Location = new System.Drawing.Point(392, 112);   
124this.btnDisconnect.Name = "btnDisconnect";   
125this.btnDisconnect.Size = new System.Drawing.Size(64, 32);   
126this.btnDisconnect.TabIndex = 7;   
127this.btnDisconnect.Text = "断开";   
128this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);   
129//   
130// clientName   
131//   
132this.clientName.Location = new System.Drawing.Point(96, 8);   
133this.clientName.Name = "clientName";   
134this.clientName.TabIndex = 8;   
135this.clientName.Text = "name";   
136//   
137// btnConnect   
138//   
139this.btnConnect.Location = new System.Drawing.Point(392, 56);   
140this.btnConnect.Name = "btnConnect";   
141this.btnConnect.Size = new System.Drawing.Size(64, 32);   
142this.btnConnect.TabIndex = 9;   
143this.btnConnect.Text = "连接";   
144this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);   
145//   
146// Form1   
147//   
148this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);   
149this.ClientSize = new System.Drawing.Size(464, 309);   
150this.Controls.Add(this.btnConnect);   
151this.Controls.Add(this.clientName);   
152this.Controls.Add(this.btnDisconnect);   
153this.Controls.Add(this.statusBar1);   
154this.Controls.Add(this.btnSend);   
155this.Controls.Add(this.ChatOut);   
156this.Controls.Add(this.checkBox1);   
157this.Controls.Add(this.rtbChatIn);   
158this.Controls.Add(this.lbChatters);   
159this.Name = "Form1";   
160this.Text = "Form1";   
161this.ResumeLayout(false); 
162
163}   
164#endregion 
165
166/// <summary>   
167/// 应用程序的主入口点。   
168/// </summary>   
169[STAThread]   
170static void Main()   
171{   
172Application.Run(new Form1());   
173} 
174
175private void EstablishConnection()   
176{   
177statusBar1.Text = "正在连接到服务器";   
178  
179try   
180{   
181clientsocket = new TcpClient(serveraddress,serverport);   
182ns = clientsocket.GetStream();   
183sr = new StreamReader(ns);   
184connected = true;   
185  
186}   
187catch (Exception)   
188{   
189MessageBox.Show("不能连接到服务器!","错误",   
190MessageBoxButtons.OK, MessageBoxIcon.Exclamation);   
191statusBar1.Text = "已断开连接";   
192}   
193} 
194
195private void RegisterWithServer()   
196{   
197lbChatters.Items.Clear(); 
198
199clientname = clientName.Text;   
200try   
201{   
202string command = "CONN|" + clientname; //+"\r\n";   
203Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());   
204ns.Write(outbytes,0,outbytes.Length); 
205
206  
207string serverresponse = sr.ReadLine();   
208serverresponse.Trim();   
209string[] tokens = serverresponse.Split('|');   
210if(tokens[0] == "LIST")   
211{   
212statusBar1.Text = "已连接";   
213btnDisconnect.Enabled = true;   
214}   
215if(tokens[1] != "")   
216{   
217for(int n=1; n&lt;tokens.Length;n++)   
218lbChatters.Items.Add(tokens[n].Trim(new char[]{'\r','\n'}));   
219}   
220this.Text = clientname + ":已连接到服务器"; 
221
222}   
223catch (Exception ex)   
224{   
225MessageBox.Show("注册时发生错误!"+ex.Message,"错误",   
226MessageBoxButtons.OK, MessageBoxIcon.Exclamation);   
227connected = false;   
228}   
229} 
230
231private void ReceiveChat()   
232{   
233bool keepalive = true;   
234while (keepalive)   
235{   
236try   
237{   
238Byte[] buffer = new Byte[1024]; // 2048???   
239ns.Read(buffer,0,buffer.Length);   
240string chatter = System.Text.Encoding.ASCII.GetString(buffer);   
241string[] tokens = chatter.Split(new Char[]{'|'}); 
242
243if (tokens[0] == "CHAT")   
244{   
245rtbChatIn.AppendText(tokens[1]);   
246// if(logging)   
247// logwriter.WriteLine(tokens[1]);   
248}   
249if (tokens[0] == "PRIV")   
250{   
251rtbChatIn.AppendText("Private from ");   
252rtbChatIn.AppendText(tokens[1].Trim() );   
253rtbChatIn.AppendText(tokens[2] + "\r\n");   
254// if(logging)   
255// {   
256// logwriter.Write("Private from ");   
257// logwriter.Write(tokens[1].Trim() );   
258// logwriter.WriteLine(tokens[2] + "\r\n");   
259// }   
260}   
261if (tokens[0] == "JOIN")   
262{   
263rtbChatIn.AppendText(tokens[1].Trim() );   
264rtbChatIn.AppendText(" has joined the Chat\r\n");   
265// if(logging)   
266// {   
267// logwriter.WriteLine(tokens[1]+" has joined the Chat");   
268// }   
269string newguy = tokens[1].Trim(new char[]{'\r','\n'});   
270lbChatters.Items.Add(newguy);   
271}   
272if (tokens[0] == "GONE")   
273{   
274rtbChatIn.AppendText(tokens[1].Trim() );   
275rtbChatIn.AppendText(" has left the Chat\r\n");   
276// if(logging)   
277// {   
278// logwriter.WriteLine(tokens[1]+" has left the Chat");   
279// }   
280lbChatters.Items.Remove(tokens[1].Trim(new char[]{'\r','\n'}));   
281}   
282if (tokens[0] == "QUIT")   
283{   
284ns.Close();   
285clientsocket.Close();   
286keepalive = false;   
287statusBar1.Text = "服务器端已停止";   
288connected= false;   
289btnSend.Enabled = false;   
290btnDisconnect.Enabled = false;   
291}   
292}   
293catch(Exception){}   
294}   
295} 
296
297private void QuitChat()   
298{   
299if(connected)   
300{   
301try   
302{   
303string command = "GONE|" + clientname;   
304Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());   
305ns.Write(outbytes,0,outbytes.Length);   
306clientsocket.Close();   
307}   
308catch(Exception ex)   
309{   
310MessageBox.Show(ex.Message);   
311}   
312}   
313// if(logging)   
314// logwriter.Close();   
315if(receive != null &amp;&amp; receive.IsAlive)   
316receive.Abort();   
317this.Text = "客户端";   
318  
319connected = false; 
320
321} 
322
323private void btnSend_Click(object sender, System.EventArgs e)   
324{   
325if(connected)   
326{   
327try   
328{   
329string command = "CHAT|" + clientname+": "+ChatOut.Text+"\r\n";   
330Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());   
331ns.Write(outbytes,0,outbytes.Length);   
332//clientsocket.Close();   
333}   
334catch(Exception ex)   
335{   
336MessageBox.Show(ex.Message);   
337}   
338}   
339} 
340
341private void btnConnect_Click(object sender, System.EventArgs e)   
342{   
343EstablishConnection();   
344RegisterWithServer();   
345if(connected)   
346{   
347receive = new Thread(new ThreadStart(ReceiveChat));   
348receive.Start();   
349}   
350} 
351
352private void btnDisconnect_Click(object sender, System.EventArgs e)   
353{   
354QuitChat();   
355}   
356}   
357}</clients.count;n++)>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus