這是c#的代碼,經過測試的,本來想把源程序都放上來,可以我用的是vs2005(而且現在又壞了,系統出問題了),下面是程序的主要源代碼,不包含一些自動生成的代碼.這些代碼是根據一個開源的C#socket程序改編的,而且我已經寫了比較詳細的註釋了,如果你看了這些代碼還是發現有問題,可以向我索取完整的源程序:
[1b]把源文件傳上來,大家可以下載(gmail又打不開了,不能給留email的同學發了,自己下載吧):
[img]/Files/BeyondPic/2006-10/30/download.gif[/img]
[url=http://www.roading.net/blog/attachments/month_0604/82006420113027.rar]點擊下載此文件[/url]
[/1b]
//--------------------------------
//---------------------------------------------------------------------------------------------------------------
//form1.cs
using System;
using System.IO;
using System.Drawing;
using System.Collections;//ArrayList引用到這個命名空間的類
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ChatServer//服務器端命名空間
{
///
/// Form1 的摘要說明。
///
public class Form1 : System.Windows.Forms.Form
{
private int listenport = 9050;//監聽端口
private TcpListener listener;//監聽者
private ArrayList clients;//所有的client
private Thread processor;//處理線程
private Socket clientsocket;//client套接字
private Thread clientservice;//client的服務
private System.Windows.Forms.ListBox lbClients;
private System.Windows.Forms.Label label1;//顯示在線人員的List控件
private TcpClient tclient;
private NetworkStream ns;
private System.Windows.Forms.Button button1;
///
/// 必需的設計器變量。
///
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Windows 窗體設計器支持所必需的
//
InitializeComponent();
Thread.CurrentThread.IsBackground = true;
//
// TODO: 在 InitializeComponent 調用後添加任何構造函數代碼
//
clients = new ArrayList();//新建一個ArrayList類型用以存儲所有的client
processor = new Thread(new ThreadStart(StartListening));//新建一個處理線程
processor.Start();//線程開始
//
}
///
/// 清理所有正在使用的資源。
///
protected override void Dispose( bool disposing )
{
int c = clients.Count;
for(int n=0; n
{
components.Dispose();
}
}
base.Dispose( disposing );
}
///
/// 開始監聽
///
private void StartListening()
{
IPAddress ipAddress = Dns.Resolve(Dns.GetHostName()).AddressList[0];
//IPAddress ipAddress = IPAddress.Parse("192.168.0.132");
label1.Text=ipAddress.ToString();
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, listenport);
listener = new TcpListener(ipLocalEndPoint);
listener.Start();
while (true)
本文轉自:http://www.5uflash.com/flashjiaocheng/Flashyingyongkaifa/869.html