服务端的代码
unit Server;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls,Winsock;
type
TSyncThread =class(TThread)
protected
procedure execute ; override;
public
procedure AddRecvMsg;
end;
TMainFrame = class(TForm)
BtnStartServer: TButton;
ListBoxUsers: TListBox;
ListBoxMsg: TListBox;
BtnExitServer: TButton;
LbMsg: TLabel;
EditMsg: TEdit;
BtnSendMsg: TButton;
StatusBarServer: TStatusBar;
procedure BtnStartServerClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtnExitServerClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtnSendMsgClick(Sender: TObject);
procedure EditMsgEnter(Sender: TObject);
private
{ Private declarations }
ThreadListen:TSyncThread;
public
{ Public declarations }
end;
var
MainFrame: TMainFrame;
ServerSocket :TSocket;
RecvSocket :TSocket;
BlockBuf:Array [0..1024*4-1] of char;
const BufLength =1024*4;
implementation
{$R *.dfm}
procedure TSyncThread.execute;
var
ra:SOCKADDR_IN;
ra_len:Integer;
begin
ra_len:=sizeof(ra);
RecvSocket:=accept(ServerSocket,@ra,@ra_len);
while (true) do
begin
recv(RecvSocket,BlockBuf,BufLength,0);
Synchronize(AddRecvMsg);
MainFrame.Update;
end;
;
end;
procedure TSyncThread.AddRecvMsg;
begin
MainFrame.ListBoxUsers.Items.Add('Client');
MainFrame.ListBoxMsg.Items.Add(BlockBuf);
end;
procedure TMainFrame.BtnStartServerClick(Sender: TObject);
var
ca:SOCKADDR_IN;
begin
ServerSocket:=Socket(PF_INET,SOCK_STREAM,IPPROTO_IP);
if ServerSocket=INVALID_SOCKET then
begin
StatusBarServer.SimpleText:='Creating Accept Socket Server Error';
Exit;
end
else
ca.sin_family:=PF_INET;
ca.sin_port:=htons(3000);
ca.sin_addr.S_addr:=INADDR_ANY;
if Bind(ServerSocket,ca,sizeof(ca))=SOCKET_ERROR then
begin
StatusBarServer.SimpleText:='Binding the Server Socket Error';
CloseSocket(ServerSocket);
exit;
end
else
StatusBarServer.SimpleText:='Binding the Server Socket Succeed!';
try
listen(ServerSocket,5);
except
on e:Exception do
showmessage(e.Message);
end;
BtnStartServer.Enabled:=false;
ThreadListen:=TsyncThread.Create(false);
end;
procedure TMainFrame.FormCreate(Sender: TObject);
var
aWSAData:TWSADATA;
begin
if WSAStartup($0101,aWSAData)<>0 then
raise Exception.Create('Can not load the Socket Dll#13');
end;
procedure TMainFrame.BtnExitServerClick(Sender: TObject);
begin
Close;
end;
procedure TMainFrame.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if ServerSocket<>INVALID_SOCKET then
closesocket(ServerSocket);
if WSACleanup<>0 then
MessageBox(Handle,'Clean the Winsock dll wrong','Error Messge',MB_OK);
end;
procedure TMainFrame.BtnSendMsgClick(Sender: TObject);
begin
strpcopy(BlockBuf,MainFrame.EditMsg.Text);
send(RecvSocket,BlockBuf,BufLength,0);
ListBoxMsg.Items.Add(BlockBuf);
ListBoxUsers.Items.Add('Me');
end;
procedure TMainFrame.EditMsgEnter(Sender: TObject);
begin
BtnSendMsgClick(Sender);
end;
end.