下面的代码是监听一个端口,通过消息来读信息:
uses Winsock;
connect
WM_SOCK = WM_USER + 11; //自定义端口消息
GETUDPPORT = 6601;
function StartNetServer:boolean;
var
TempWSAData: TWSAData;
begin
result:=true;
// 初始化SOCKET
if WSAStartup(2, TempWSAData)<>0 then
msg('SOCKET初始化错误',merr);
s := Socket(AF_INET, SOCK_DGRAM, 0);
if (s = INVALID_SOCKET) then //Socket创建失败
begin
msg('Socket创建失败',merr);
result:=false;
CloseSocket(s);
exit;
end;
//发送方SockAddr绑定
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := INADDR_ANY;
addr.sin_port := htons(GETUDPPORT);
if Bind(s, addr, sizeof(addr)) <> 0 then
begin
msg('监听端口 '+inttostr(GETUDPPORT)+' 失败。',merr);
result:=false;
CloseSocket(s);
exit;
end;
WSAAsyncSelect(s, frm_window.Handle , WM_SOCK, FD_READ);
end;
//------------------------------------------
Tfrm_window = class(TForm)
private
{ Private declarations }
procedure ReadData(var Message: TMessage);message WM_SOCK;//接受到的端口信息处理
public
end;
procedure Tfrm_window.ReadData(var Message: TMessage);
var
buffer: Array [1..4096] of char;
len: integer;
flen: integer;
value: string;
begin
flen:=sizeof(FSockAddrIn);
if WSAGetSelectEvent(Message.LParam) = FD_READ then
begin
len := recvfrom(s, buffer, sizeof(buffer), 0, FSockAddrIn, flen);
value := copy(buffer, 1, len);
//value是你接受到的东西,自己根据内容进行处理
end;
end;