现在的位置: 首页 > 综合 > 正文

我写的一个简单的聊天程序(bcb)

2013年07月12日 ⁄ 综合 ⁄ 共 16477字 ⁄ 字号 评论关闭

服务器端: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="传送文件结束!";
  }
}
//---------------------------------------------------------------------------

 

抱歉!评论已关闭.