Internet盛行的今天,网上聊天已成为一种时尚。同时,各单位已建成了自己的局域网;能否在局域网上实现聊天呢?可以,网上到处都有这种工具。当然,我们可以拥有自己版权的聊天工具......
现在的界面如下:
源程序如下:
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, NMUDP, Menus, ComCtrls,WinSock; file://增加WinSock
type
TForm1 = class(TForm)
NMUDP1: TNMUDP;
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
Edit1: TEdit;
BitBtn1: TBitBtn;
Memo1: TMemo;
Panel3: TPanel;
Panel4: TPanel;
ListBox1: TListBox;
Button1: TButton;
Button2: TButton;
procedure FormShow(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure NMUDP1DataReceived(Sender: TComponent; NumberBytes: Integer;
FromIP: String; Port: Integer);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
ComputerName: array[0..127] of Char;
implementation
{$R *.DFM}
procedure TForm1.FormShow(Sender: TObject);
var
sz: dword;
begin
sz := SizeOf(Computername);
GetComputerName(ComputerName, sz);//得到本机的标识
ListBox1.Items.Clear;
ListBox1.Items.Add('大家');//在网友清单中,增加"大家"和
ListBox1.Items.Add(ComputerName);//本机名称
ListBox1.ItemIndex:=0;
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
var
MyStream: TMemoryStream;
TmpStr: String;
i:integer;
Begin
if Edit1.Text<>'' then file://如果所说的内容不为空,则发送。
begin
NMUDP1.ReportLevel := Status_Basic;
NMUDP1.RemotePort :=8888;//端口为:8888,可以自己定义,但必须与LocalPort相一致。
if ListBox1.Items[ListBox1.ItemIndex]=ComputerName then
Edit1.Text:=ComputerName+'自言自语道:'+Edit1.Text file://如果和自己对话.
Else
Edit1.Text:=ComputerName+'对'+ListBox1.Items[listbox1.itemindex]+'说:'+Edit1.Text;
TmpStr :=Edit1.text;
MyStream := TMemoryStream.Create;
try
MyStream.Write(TmpStr[1], Length(Edit1.Text));
if ListBox1.ItemIndex=0 then
begin
for i:=1 to ListBox1.Items.Count-1 do file://如果选择"大家",则对所有的网友发送信息
begin
NMUDP1.RemoteHost :=ListBox1.Items[i];//远程主机的名称或地址.
NMUDP1.SendStream(MyStream);//发送信息.
End;
end
else 如果私聊
begin
NMUDP1.RemoteHost :=ListBox1.Items[ListBox1.itemindex]; file://仅对所选中的网友.
NMUDP1.SendStream(MyStream);
End;
finally
MyStream.Free;
end;
Edit1.Text:='';
Edit1.SetFocus;
end else
Edit1.SetFocus;
end;