设为首页 加入收藏

TOP

编写简单的C/S聊天程序
2017-10-10 12:07:26 】 浏览:4277
Tags:编写 简单 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;

 运行图:

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇DELPHI版传奇引擎学习菜鸟篇(appl.. 下一篇学习笔记 :DrawText

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

最新文章

热门文章

C 语言

C++基础

windows编程基础

linux编程基础

C/C++面试题目