Tserversocker和Tclientsocket的简单问题。急!(300分)

  • 主题发起人 主题发起人 JoshuaChan
  • 开始时间 开始时间
J

JoshuaChan

Unregistered / Unconfirmed
GUEST, unregistred user!
小弟是第一次用这两个控件。想要一个很简单的示例!
要求:客户端发一条信息,服务端接收,MESSAGEBOX该信息的字符串内容!
但小弟怎么也做不到!程序经常出现“接收了一个非套接字的错误”等的错误信息!
想请各位写一个简单例子给我!!
THANK YOU!
 
看看delphi自带的demo就行了。

unit file:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ScktComp;

type
TForm1 = class(TForm)
ClientSocket1: TClientSocket;
ServerSocket1: TServerSocket;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
ClientSocket1.Open;
Sleep(2000); //wait for connect to serversocket
Application.ProcessMessages;
ClientSocket1.Socket.SendText('this is a test') ;
ClientSocket1.Close;
end;

procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
ShowMessage(Socket.ReceiveText);
end;

end.


form file:
object Form1: TForm1
Left = 192
Top = 114
Width = 275
Height = 269
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 88
Top = 120
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
object ClientSocket1: TClientSocket
Active = False
Address = '127.0.0.1'
ClientType = ctNonBlocking
Port = 9999
Left = 104
Top = 64
end
object ServerSocket1: TServerSocket
Active = True
Port = 9999
ServerType = stNonBlocking
OnClientRead = ServerSocket1ClientRead
Left = 152
Top = 64
end
end
 
一般把连接和发送分开,先连接,
发送时先判断一下CLIENT是否已经ACTVE了。
如果ACTIVE了,再发。

好象Application.ProcessMessages;可以不用,
非阻塞模式就这点好,不等待。
 
1.在接受的电脑上运行ServerSocket程序,直接指定端口5555,Active:=true,即可。

2.发送端连接接受端:
clientsocket1.host:='接受端电脑名字';
clientsocket1.port:=5555;
clientsocket1.active:=true;

3.发送消息:
clientsocket1.sendtext('嘿嘿!');

4.接受消息:
onclientwrite事件:
socket.readtext(buf,1024);
showmessage(string(pchar(buf)));
 
同意楼上的,必须先serversocket.active:=true
在clientsocket.active;=true
按步骤来!!不要急!
 

Similar threads

后退
顶部