winsock2.pas 的下载地址http://jungla.dit.upm.es/~bti/files/winsock2.pas
我给你调试通过了昨天没有DELPHI
.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, WinSock2, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
Type
TSocketThread=class(TThread)
private
Memo:TMemo;
tBuff:Array[0..8196] of Byte;
procedure WriteMemo;
protected
procedure Execute;override;
public
Constructor Create(vMemo:TMemo);
end;
Var
SocketThread:TSocketThread;
//客户端
procedure ClientOpen(Var Buff; Len:Integer);
var
buf:TWSABUF;
SendBytes
WORD;
tBuff:Array[0..8196] of Byte;
hRet:Integer;
Data: TWSAData;
Addr: TSockaddrIn;
m_Socket:TSocket;
begin
WSAStartup(MakeWord(2,2), Data);
m_Socket := WSASocket(AF_INET, SOCK_STREAM ,0,nil,0,0);
if m_Socket=INVALID_SOCKET then
Exit;
Addr.sin_family := AF_INET;
Addr.sin_addr.s_addr := inet_addr('127.0.0.1');
Addr.sin_port := htons(8000);
connect(m_Socket,@Addr,Sizeof(Addr));
Buf.Buf:=@tBuff;
Buf.Len:=8196;
{做你的处理部分}
CopyMemory(@tBuff,PChar(@Buff),Len);
hRet:=WSASend(m_Socket,@Buf,1,@SendBytes,0,nil,nil);
if hRet=Socket_Error then
Exit;
{做你的处理部分}
{从服务端接收数据使用WSARecv使用方法参考服务端
WSARecv(m_Socket,@Buf,1,@RecvBytes,Flag,nil,nil);
}
CloseSocket(m_Socket);
WSACleanup();
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
SocketThread:=TSocketThread.Create(Memo1);
end;
procedure TForm1.Button2Click(Sender: TObject);
Var
Str:String;
begin
Str:=Edit1.Text;
ClientOpen(PChar(Str)^,Length(Str));
end;
{ TSocketThread }
constructor TSocketThread.Create(vMemo:TMemo);
begin
Inherited Create(true);
Self.FreeOnTerminate:=true;
Memo:=vMemo;
Self.Resume;
end;
procedure TSocketThread.Execute;
var
buf:TWSABUF;
RecvBytes,Flag
WORD;
hRet:Integer;
Data: TWSAData;
Addr: TSockaddrIn;
AcceptSocket,m_Socket:TSocket;
begin
WSAStartup(MakeWord(2,2), Data);
m_Socket := WSASocket(AF_INET, SOCK_STREAM ,0,nil,0,0);
if m_Socket=INVALID_SOCKET then
Exit;
Addr.sin_family := AF_INET;
Addr.sin_addr.s_addr := htonl(INADDR_ANY);
Addr.sin_port := htons(8000);
bind(m_Socket,@Addr,Sizeof(Addr));
Listen(m_Socket,5);
While Not Terminated do
begin
AcceptSocket:=WSAAccept(m_Socket,nil,nil,nil,0);
if AcceptSocket=INVALID_SOCKET then
Exit;
Buf.Buf:=@tBuff;
Buf.Len:=8196;
Flag:=0;
hRet:=WSARecv(AcceptSocket,@Buf,1,@RecvBytes,@Flag,nil,nil);
{做你的处理部分}
Synchronize(WriteMemo);
{发送数据到客户段使用WSASend,Socket参数使用AcceptSocket
如:WSASend(AcceptSocket,Buf,1,SendOfBytes,0,nil,nil);
}
end;
CloseSocket(m_Socket);
WSACleanup();
end;
procedure TSocketThread.WriteMemo;
begin
Memo.Lines.Add(StrPas(PChar(@tBuff)));
end;
end.