码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-12-15 22:50:44      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

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

主要用到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;

 运行图:

技术分享

 

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

标签:

原文地址:http://www.cnblogs.com/hkleak/p/5049533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!