编写简单的C/S聊天程序

找了点资料看了下,于是自己动手做了一个练习一下,

主要用到TServerSocket和TClientSocket这个控件。

客户端:

var
  Form1: TForm1;
  NewTime:string;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  ClientSocket1.Host:=Trim(Edit1.Text);      //连接服务端地址
  ClientSocket1.Port:=57124;  //连接的端口号
  ClientSocket1.Open;  //开始连接
  Button1.Enabled:=False;
end;

procedure TForm1.ClientSocket1Read(Sender: TObject;
  Socket: TCustomWinSocket);
  var
    Str:string;
begin
    //读取服务端发过来的数据
    str:=ClientSocket1.Socket.ReceiveText;
    Memo1.Lines.Add(Str);

end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Msg:string;
begin
  Msg:=Trim(Edit2.Text);
  Memo1.Lines.Add('王四:' + NewTime + #10);
  Memo1.Lines.Add(Msg);
  ClientSocket1.Socket.SendText('王四:' + NewTime +#13#10);
  ClientSocket1.Socket.SendText(Msg); //发送给服务端


end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
   NewTime:=TimeToStr(Now);

end;

 

服务端:

var
  Form1: TForm1;
  NewTime:string;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  ServerSocket1.Port:=57124; //监听端口
  ServerSocket1.Open;  //开始监听
  Button1.Enabled:=False;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Str:string;
  i : integer;
begin
  Str:=Trim(Edit2.Text);
   for i:=0 to ServerSocket1.Socket.ActiveConnections-1 do
  begin
    Memo1.Lines.Add('张三:' + NewTime + #10);
    Memo1.Lines.Add(Str);
    ServerSocket1.Socket.Connections[i].SendText('张三:' + NewTime +#13#10);    //发送数据
    ServerSocket1.Socket.Connections[i].SendText(Str);
  end;

end;

procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
  Socket: TCustomWinSocket);   //读取客服端发来的数据
  var
    Msg:string;
begin
  Msg:=Socket.ReceiveText;
  Memo1.Lines.Add(Msg);


end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  NewTime:=TimeToStr(Now);
end;

 运行图:

 

posted @ 2015-12-15 21:11  We3sT  阅读(1793)  评论(0编辑  收藏  举报