我寫的一個簡單的聊天程序(bcb)

服務器端:server.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
AnsiString NowlogName="";
AnsiString NowlogHost="";
AnsiString NowlogAddress="";
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
 Memo1->Clear();
 ListBox1->Clear();
 ListBox2->Clear();
 ListBox3->Clear();
 ServerSocket1->Active=true;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormDestroy(TObject *Sender)
{
 Memo1->Clear();
 ListBox1->Clear();
 ListBox2->Clear();
 ListBox3->Clear();
 AnsiString SysInfo;
 SysInfo="["+TimeToStr(Now())+"]"+" 與服務器失去連接!請重新連接!";
 int M=0;
 M=ServerSocket1->Socket->ActiveConnections;
 for(int i=0;i<M;i++)
 {
  ServerSocket1->Socket->Connections[i]->SendText(SysInfo);
 }
 ServerSocket1->Active=false;
 ServerSocket1->Close();
 Form1->Close();

}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerSocket1ClientRead(TObject *Sender,
      TCustomWinSocket *Socket)
{
 NowlogHost=Socket->RemoteHost;
 NowlogAddress=Socket->RemoteAddress;
 AnsiString Data=Socket->ReceiveText(); //接收用戶發送的信息
 AnsiString SubData1=Data.SubString(Data.Length()-7,8); //分析信息
 AnsiString SubData2=Data.SubString(1,Data.Length()-8);
 if(SubData1=="@login@@") //如果是用戶登陸的信息
  {
   ListBox1->Items->Add(SubData2); //用戶信息加入到用戶列表
   ListBox2->Items->Add(NowlogAddress);
   ListBox3->Items->Add(NowlogHost);
   AnsiString SysInfo="["+TimeToStr(Now())+"]"+SubData2+" 加入了會議!";//顯示系統信息
   Memo1->Lines->Add(SysInfo);
   if(ServerSocket1->Socket->ActiveConnections)
     for(int i=0;i<ServerSocket1->Socket->ActiveConnections;i++)
//       ServerSocket1->Socket->Connections[i]->SendText(SubData2+"@login@@");
       ServerSocket1->Socket->Connections[i]->SendText("@login@@"+SubData2+"@"+NowlogHost+"@"+NowlogAddress);

  }
 else if(SubData1=="@logout@") //如果是用戶退出會議
  {
   int Index1=ListBox1->Items->IndexOf(SubData2); //從用戶列表中刪除該用戶信息
   ListBox1->Items->Delete(Index1);
   int Index2=ListBox2->Items->IndexOf(NowlogAddress);
   ListBox2->Items->Delete(Index2);
   int Index3=ListBox3->Items->IndexOf(NowlogHost);
   ListBox3->Items->Delete(Index3);
   Memo1->Lines->Add("["+TimeToStr(Now())+"]"+SubData2+" 退出了會議!"); //顯示系統信息
   if(ServerSocket1->Socket->ActiveConnections)
     for(int i=0;i<ServerSocket1->Socket->ActiveConnections;i++)
//       ServerSocket1->Socket->Connections[i]->SendText(SubData2+"@logout@");
       ServerSocket1->Socket->Connections[i]->SendText("@logout@"+SubData2+"@"+NowlogHost+"@"+NowlogAddress);
  }
 else
  {
   Data="["+TimeToStr(Now())+"]"+Data; //加入系統時間
   Memo1->Lines->Add(Data);
   //向所有用戶轉發信息
   if(ServerSocket1->Socket->ActiveConnections)
     for(int i=0;i<ServerSocket1->Socket->ActiveConnections;i++)
       ServerSocket1->Socket->Connections[i]->SendText(Data);
  }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Memo1Change(TObject *Sender)
{
 if(Memo1->Lines->Count>=100)
  Memo1->Lines->Clear();
}
//---------------------------------------------------------------------------

客戶端:client.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include "iostream.h"
#include "io.h"
#include "time.h"
#include "stdio.h"
#include "alloc.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
AnsiString yourName="yourName";
AnsiString IP="255.255.255.0";
AnsiString HostName="";
AnsiString NowlogName="";
AnsiString NowlogHost="";
AnsiString NowlogAddress="";
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
 Memo1->Clear();
 Memo2->Clear();
 Memo3->Clear();
 Memo4->Clear();
 BitBtn6->Enabled=false;
 Edit1->Text="";
 Edit2->Text="dy-02";
 StaticText1->Caption="";
 StaticText5->Caption="";
 StaticText6->Caption="";
 StaticText7->Caption="";
 Panel1->Caption="私聊對象:" ;
//---------------------------------------
 //獲取本地IP地址及主機名
 WORD wVersionRequested;
 WSADATA wsaData;
 //Start up WinSock
 wVersionRequested = MAKEWORD(1, 1);
 WSAStartup(wVersionRequested, &wsaData);

 hostent *p;
 char s[128];
 char *p2;
//Get the computer name
 gethostname(s, 128);
 p = gethostbyname(s);
 StaticText5->Caption=p->h_name;
 //Get the IpAddress
 p2 = inet_ntoa(*((in_addr *)p->h_addr));
 StaticText6->Caption=p2;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BitBtn4Click(TObject *Sender)
{
 Memo3->Clear();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BitBtn2Click(TObject *Sender)
{
 Memo1->Clear();
}
//---------------------------------------------------------------------------
//連接服務器
void __fastcall TForm1::ClientSocket1Connect(TObject *Sender,
      TCustomWinSocket *Socket)
{
 StatusBar1->SimpleText="成功連接到服務器"+ClientSocket1->Host;;
 ClientSocket1->Socket->SendText(yourName+"@login@@");
 StaticText7->Caption=DateToStr(Now())+" "+Time();
}
//---------------------------------------------------------------------------
//發送信息
void __fastcall TForm1::BitBtn1Click(TObject *Sender)
{
 if(Memo2->Lines->Text=="")
   Application->MessageBox("錯誤, 不能發空信息!","提示",MB_OK);
 else
  {
   AnsiString Data;
   Data=yourName+":"+Memo2->Lines->Text;
   ClientSocket1->Socket->SendText(Data);
//   Memo1->Lines->Add(Data);
   Memo2->Lines->Clear();
   Memo2->SetFocus();
  }
}
//---------------------------------------------------------------------------
//接收服務器發送過來的信息
void __fastcall TForm1::ClientSocket1Read(TObject *Sender,
      TCustomWinSocket *Socket)
{
 int i=0;
 AnsiString ch="";
 NowlogName="";
 NowlogHost="";
 NowlogAddress="";

 AnsiString Data=Socket->ReceiveText(); //接收用戶發送的信息
 AnsiString SubData1=Data.SubString(1,8); //分析信息
 if(SubData1=="@login@@") //如果是用戶登陸的信息
  {
   for(i=9;(ch=Data.SubString(i,1))!="@";i++)
    NowlogName+=ch;
   for(   ;(ch=Data.SubString(i+1,1))!="@";i++)
    NowlogHost+=ch;
   NowlogAddress=Data.SubString(i+1,18);
   ListBox1->Items->Add(NowlogName); //用戶信息加入到用戶列表
   ListBox2->Items->Add(NowlogAddress);
   ListBox3->Items->Add(NowlogHost);
   AnsiString SysInfo="["+TimeToStr(Now())+"] "+NowlogName+"  加入了會議!";//顯示系統信息
   Memo1->Lines->Add(SysInfo);
  }
 else if(SubData1=="@logout@") //如果是用戶退出會議
  {
   for(i=9;(ch=Data.SubString(i,1))!="@";i++)
    NowlogName+=ch;
   for(   ;(ch=Data.SubString(i+1,1))!="@";i++)
    NowlogHost+=ch;
   NowlogAddress=Data.SubString(i+1,18);
   int Index1=ListBox1->Items->IndexOf(NowlogName); //從用戶列表中刪除該用戶信息
   ListBox1->Items->Delete(Index1);
   int Index2=ListBox2->Items->IndexOf(NowlogAddress);
   ListBox2->Items->Delete(Index2);
   int Index3=ListBox3->Items->IndexOf(NowlogHost);
   ListBox3->Items->Delete(Index3);
   Memo1->Lines->Add("["+TimeToStr(Now())+"] "+NowlogName+"  退出了會議!"); //顯示系統信息
  }
 else
   Memo1->Lines->Add(Data);

}
//---------------------------------------------------------------------------
//私聊空間或傳送文件選定對象
void __fastcall TForm1::ListBox1Click(TObject *Sender)
{
 if(ClientSocket2->Active)
  {
   ClientSocket2->Active=false;
   ClientSocket2->Close();
  }
 int Index=ListBox1->ItemIndex;
 IP=ListBox2->Items->Strings[Index];
 HostName=ListBox3->Items->Strings[Index];
 Panel1->Caption="私聊對象:"+ListBox1->Items->Strings[Index];
 StaticText1->Caption=ListBox1->Items->Strings[Index];
 ClientSocket2->Host=HostName;
 ClientSocket2->Address=IP;
 ClientSocket2->Port=2222;
 ClientSocket2->Active=true;
 BitBtn3->Enabled=true;

}
//---------------------------------------------------------------------------
//在私聊空間發送信息給選定用戶
void __fastcall TForm1::BitBtn3Click(TObject *Sender)
{
 if(Memo4->Lines->Text=="")
   Application->MessageBox("錯誤, 不能發空信息!","提示",MB_OK);
 else
  {
   AnsiString Data;
   Data=yourName+"對"+StaticText1->Caption+"說:"+Memo4->Lines->Text;
   ClientSocket2->Socket->SendText(Data);
//   Memo3->Lines->Add(Data);
   Memo4->Lines->Clear();
   Memo4->SetFocus();
  }
}
//---------------------------------------------------------------------------
//選擇要傳送的文件
void __fastcall TForm1::BitBtn5Click(TObject *Sender)
{
 if(NMStrm1->Connected)
   NMStrm1->Disconnect();
 if(OpenDialog1->Execute())
  {
   Edit1->Text=OpenDialog1->FileName;
   BitBtn6->Enabled=true;
  }
}
//---------------------------------------------------------------------------
//登陸到服務器
void __fastcall TForm1::Button1Click(TObject *Sender)
{
 if(ClientSocket1->Active)
  {
    ClientSocket1->Active=false;
    ClientSocket1->Close();
  }
 ListBox1->Items->Clear();
 ListBox2->Items->Clear();
 Memo1->Clear();
 Memo3->Clear();
 if(InputQuery("登陸到服務器","請輸入你的暱稱:",yourName)) //輸入暱稱
  {
   StatusBar1->SimpleText="正在連接服務器...";

   ClientSocket1->Address=MaskEdit1->Text;
   ClientSocket1->Host=Edit2->Text;
   ClientSocket1->Port=4000;
   ClientSocket1->Active=true;
   BitBtn1->Enabled=true;
   BitBtn3->Enabled=true;
  }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button2Click(TObject *Sender)
{
 ListBox1->Items->Clear();
 ListBox2->Items->Clear();
 ListBox3->Items->Clear();
 ClientSocket1->Active=false;
 StatusBar1->SimpleText="連接中斷...";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormDestroy(TObject *Sender)
{
 WSACleanup();
 ServerSocket1->Close();
 ClientSocket1->Close();
 ClientSocket2->Close();
 NMStrm1->Cancel();
 NMStrmServ1->Cancel();
 Close();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N2Click(TObject *Sender)
{
 TabbedNotebook1->PageIndex=3;
 StatusBar1->SimpleText="傳送文件...";
 Edit1->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::N1Click(TObject *Sender)
{
 TabbedNotebook1->PageIndex=2;
 StatusBar1->SimpleText="私聊空間...";
 Memo4->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::TabbedNotebook1Change(TObject *Sender, int NewTab,
      bool &AllowChange)
{
 if(NewTab==0)        StatusBar1->SimpleText="連接設置...";
 else if(NewTab==1)   StatusBar1->SimpleText="網絡會議...";
 else if(NewTab==2)   StatusBar1->SimpleText="私聊空間...";
 else if(NewTab==3)   StatusBar1->SimpleText="傳送文件...";
 else if(NewTab==4)   StatusBar1->SimpleText="本機信息...";
 else if(NewTab==5)   StatusBar1->SimpleText="版本信息...";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
 ListBox1->Items->Clear();
 ListBox2->Items->Clear();
 ListBox3->Items->Clear();
 ClientSocket1->Active=false;
 StatusBar1->SimpleText="連接已中斷...";
 Close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerSocket1ClientRead(TObject *Sender,
      TCustomWinSocket *Socket)
{
 AnsiString Data=Socket->ReceiveText(); //接收私聊對象發送的信息
 Memo3->Lines->Add(Data);

}
//---------------------------------------------------------------------------

void __fastcall TForm1::ClientSocket1Disconnect(TObject *Sender,
      TCustomWinSocket *Socket)
{
 ClientSocket1->Socket->SendText(yourName+"@logout@");
 ClientSocket1->Close();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ClientSocket1Error(TObject *Sender,
      TCustomWinSocket *Socket, TErrorEvent ErrorEvent, int &ErrorCode)
{
 Application->MessageBox("無法連接主機!網絡不通或者服務端未啓動!","連接失敗!",MB_OK);
 StatusBar1->SimpleText="連接服務器失敗...";
 Close();
}
//---------------------------------------------------------------------------


void __fastcall TForm1::ClientSocket2Connect(TObject *Sender,
      TCustomWinSocket *Socket)
{
 StatusBar1->SimpleText="成功連接到"+StaticText1->Caption;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ClientSocket2Disconnect(TObject *Sender,
      TCustomWinSocket *Socket)
{
 ClientSocket2->Close();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ClientSocket2Error(TObject *Sender,
      TCustomWinSocket *Socket, TErrorEvent ErrorEvent, int &ErrorCode)
{
 Application->MessageBox("無法連接到對對象!網絡不通或對方未在線!","連接失敗!",MB_OK);
 StatusBar1->SimpleText="連接對象失敗...";

}
//---------------------------------------------------------------------------

 

void __fastcall TForm1::BitBtn6Click(TObject *Sender)
{
 if(Edit1->Text=="")
  {
   Application->MessageBox("請選擇需要傳送的文件!","...",MB_OK);
   BitBtn6->Enabled=false;
  }
 else
  {
   BitBtn6->Enabled=true;
   TFileStream *MyFStream;
   MyFStream = new TFileStream(OpenDialog1->FileName, fmOpenRead);
   try
    {
     NMStrm1->Host = HostName;
     NMStrm1->FromName = Edit1->Text;
     NMStrm1->PostIt(MyFStream);
    }
   catch(...)
    {
    }
   MyFStream->Free();
  }
}
//---------------------------------------------------------------------------
//接收並保存發送過來的文件
void __fastcall TForm1::NMStrmServ1MSG(TComponent *Sender,
      const AnsiString sFrom, TStream *strm)
{
 AnsiString nmFilenameExt="";
 int count=1;
 for(count=1;count<=sFrom.Length();)
  {
   if(sFrom.SubString(count,1)==".")
    break;
   else
    count++;
  }
 nmFilenameExt=sFrom.SubString(count+1,sFrom.Length()-count);
 SaveDialog1->Title="保存文件到:";
 //設置對話框的標題
 SaveDialog1->InitialDir="//Data";
 //設置對話框的缺省路徑
 SaveDialog1->Filter="Files(*."+nmFilenameExt+")|*."+nmFilenameExt;
  //設置文件過濾器
 SaveDialog1->DefaultExt=nmFilenameExt;
 //設置缺省文件名
 if(SaveDialog1->Execute())
  {
//   StatusBar1->SimpleText="正在接收文件:"+sFrom+"...";
   TFileStream *MyFStream;
   MyFStream = new TFileStream(SaveDialog1->FileName, fmCreate);
   try
    {
     MyFStream->CopyFrom(strm, strm->Size);
    }
   catch(...)
    {
    }
   MyFStream->Free();
  }

 if(NMStrmServ1->BytesRecvd!=NMStrmServ1->BytesTotal)
  ProgressBar1->Position=(float(NMStrmServ1->BytesRecvd)/float(NMStrmServ1->BytesTotal))*100;
 else
  {
   ProgressBar1->Position=100;
//   Application->MessageBox("接收文件結束!","提示",MB_OK);
   ProgressBar1->Position=0;
   StatusBar1->SimpleText="接收文件結束!";
  }
}
//---------------------------------------------------------------------------

 

void __fastcall TForm1::BitBtn7Click(TObject *Sender)
{
   NMStrm1->Cancel();
   NMStrmServ1->Cancel();
   StatusBar1->SimpleText="傳送文件...";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::NMStrm1InvalidHost(bool &Handled)
{
 Application->MessageBox("無法識別的主機!","",MB_OK);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::NMStrm1ConnectionFailed(TObject *Sender)
{
 Application->MessageBox("連接失敗,請確認對方地址是否正確!","",MB_OK);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::NMStrm1MessageSent(TObject *Sender)
{
 if(NMStrm1->BytesSent!=NMStrm1->BytesTotal)
  StatusBar1->SimpleText="正在傳送文件:"+Edit1->Text+"...";
 else
  StatusBar1->SimpleText="傳送文件結束!";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::NMStrm1Status(TComponent *Sender,
      AnsiString Status)
{
  StatusBar1->SimpleText="Last WinSock error: "+IntToStr(NMStrm1->LastErrorNo);
  if (NMStrm1->BeenCanceled)
    StatusBar1->SimpleText="操作被取消...";
  if (NMStrm1->BeenTimedOut)
    StatusBar1->SimpleText="操作超時...";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::NMStrm1Connect(TObject *Sender)
{
  StatusBar1->SimpleText="連接成功...";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::NMStrm1Disconnect(TObject *Sender)
{
// StatusBar1->SimpleText="中斷連接...";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::NMStrm1HostResolved(TComponent *Sender)
{
  StatusBar1->SimpleText = "Host Resolved";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::NMStrmServ1ClientContact(TObject *Sender)
{
 StatusBar1->SimpleText = "Client Contacted";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::NMStrmServ1Status(TComponent *Sender,
      AnsiString Status)
{
  if (StatusBar1 != 0)
    StatusBar1->SimpleText = Status;
}
//---------------------------------------------------------------------------


void __fastcall TForm1::NMStrm1PacketSent(TObject *Sender)
{
 if(NMStrm1->BytesSent!=NMStrm1->BytesTotal)
  ProgressBar1->Position=(float(NMStrm1->BytesSent)/float(NMStrm1->BytesTotal))*100;
 else
  {
   ProgressBar1->Position=100;
//   Application->MessageBox("傳送文件結束!","提示",MB_OK);
   ProgressBar1->Position=0;
   StatusBar1->SimpleText="傳送文件結束!";
  }
}
//---------------------------------------------------------------------------

 

發佈了33 篇原創文章 · 獲贊 10 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章