Delphi, network communication, Tserversocket,tclientsocket
Now I have summed up the basic usage of the Tserversocket and tclientsocket two components, I hope to share with you.
The Clientsocket component is the client component. It is the requestor of the communication, that is, it is actively establishing a connection with the server side.
The ServerSocket component is a server-side component. It is the responder of the communication, that is, its action is listening and passively accepting the client's connection please
Ask and respond to requests.
The ServerSocket component can accept connection requests for one or more clientsocket components at the same time, and with each clientsocket component to establish a separate
connections, for individual communication. As a result, one server side can serve multiple clients.
Design ideas
This example includes a server-side program and a client program. Client programs can be run on multiple computers while connecting to the server side
Communication.
The focus of this example is to demonstrate how the client communicates with the server, and the second is how the server side identifies each client and responds to the request when multiple clients are connected to the server at the same time. To ensure that a client disconnects without affecting other clients ' communication with the server side,
While ensuring that the server side can correctly respond to the client's request, in this case a record type is declared:
Type
Client_record=record
Chandle:integer; Client socket handle
Csocket:tcustomwinsocket; Client sockets
cname:string; Client computer Name
caddress:string; Client computer IP Address
Cused:boolean; Client Online flag
End
Use this record type data to save the client's information while saving the current client's connection status. In which, CHandle saves the client socket handle to accurately locate each client that is connected to the server side, and CSocket to save the client socket, which can respond to the client. Cused records whether the current client is connected to the server side.
The following is a brief description of the properties of the component ServerSocket and Clientsocket.
Properties of ServerSocket:
· Port, which is the ports of communication, must be set. In this case, set to 1025;
· Servertypt, the server-side read and write information type, set to Stnonblocking to represent asynchronous read and write information, this example in this way.
· Threadcachesize, the maximum number of connections to the client is how many clients the server side is allowed to connect at the same time. This example uses the default value of 10.
Other properties take the default setting.
Properties of Clientsocket:
· Port, which is the ports of communication, must be the same as the server-side settings. In this case, set to 1025;
· ClientType, the client read-write information type should be the same as the server-side setting, and stnonblocking for asynchronous read-write information.
· Host, the IP address of the server to which the client will connect. Must be set, and of course it can be set dynamically in code.
Other properties take the default setting.
Program Source code:
· Server-side source code (USERVERMAIN.PAS):
<span style= "FONT-SIZE:18PX;"
>unit Uservermain; Interface uses Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, Scktcomp, Toolwin, Comctrls
, Extctrls, Stdctrls, Buttons; Const CMAX=10; Client Maximum connection number type Client_record=record Chandle:integer; Client socket handle Csocket:tcustomwinsocket; Client socket cname:string; client computer name caddress:string; Client computer IP address Cused:boolean;
Client online flag end;
Type Tfrmservermain = Class (Tform) Serversocket:tserversocket;
Controlbar1:tcontrolbar;
Toolbar1:ttoolbar;
Tbconnect:ttoolbutton;
Tbclose:ttoolbutton;
Tbdisconnected:ttoolbutton;
Edit1:tedit;
Memo1:tmemo;
Statusbar:tstatusbar;
Procedure Tbconnectclick (Sender:tobject);
Procedure Tbdisconnectedclick (Sender:tobject);
Procedure Serversocketclientread (Sender:tobject;
Socket:tcustomwinsocket);
Procedure Serversocketlisten (Sender:tobject;
Socket:tcustomwinsocket);
Procedure Serversocketclientconnect (Sender:tobject; SOcket:tcustomwinsocket);
Procedure Serversocketclientdisconnect (Sender:tobject;
Socket:tcustomwinsocket);
Procedure Tbcloseclick (Sender:tobject);
Procedure Formcreate (Sender:tobject);
Procedure Formclose (Sender:tobject; var action:tcloseaction); Procedure Serversocketgetsocket (Sender:tobject;
Socket:integer;
var clientsocket:tserverclientwinsocket);
Procedure Serversocketclienterror (Sender:tobject; Socket:tcustomwinsocket;
Errorevent:terrorevent;
var errorcode:integer); Private {Private declarations} public {public declarations} Session:array[0..cmax] of Client_record; Client connection array Sessions:integer;
Number of client connections end;
var Frmservermain:tfrmservermain; Implementation {$R *.
DFM}//Open socket connection and make socket enter the listening state procedure Tfrmservermain.tbconnectclick (Sender:tobject);
Begin Serversocket.open;
End
Closes the socket connection and no longer listens for client requests procedure Tfrmservermain.tbdisconnectedclick (Sender:tobject);
Begin Serversocket.close; Statusbar.panels[0].
Text: = Server socket connection is turned off and cannot accept client connection requests.;
End
Read information from the client procedure Tfrmservermain.serversocketclientread (sender:tobject;
Socket:tcustomwinsocket);
var I:integer;
Begin//Add the information read from the client to the Memo1 Memo1.Lines.Add (Socket.receivetext); For the i:=0 to sessions do begin//get a matching client if session[i]. CHandle = Socket.sockethandle THEN BEGIN Session[i]. Csocket.sendtext (reply client +session[i].
caddress+ ==> +edit1.text);
End
End
End
Server-side sockets Enter the listening state to monitor client connections procedure Tfrmservermain.serversocketlisten (sender:tobject;
Socket:tcustomwinsocket); Begin Statusbar.panels[0].
Text: = Wait for client to connect ...;
End
When the client connects to the server side procedure Tfrmservermain.serversocketclientconnect (sender:tobject;
Socket:tcustomwinsocket);
var I,j:integer;
Begin J:=-1; For i:=0 to sessions does begin///////If not session[i] in the existing client connection array with an interrupted client connection. Cused then begin session[i]. CHandle: = socket.sockethandle//client socket handle Session[i]. CSocket: = Socket; Client socket Session[i]. CName: = SoCket. RemoteHost; Client computer name Session[i]. CAddress: = socket.remoteaddress//client computer IP Session[i]. cused: = True;
The current position of the connection array already occupies the break;
End
J:=i;
End
If J=sessions THEN BEGIN Inc (sessions); SESSION[J].
CHandle: = Socket.sockethandle; SESSION[J].
CSocket: = Socket; SESSION[J].
CName: = Socket.remotehost; SESSION[J].
CAddress: = socket.remoteaddress; SESSION[J].
cused: = True;
End Statusbar.panels[0].
Text: = Client +socket.remotehost + already connected;
End
Procedure Tfrmservermain.serversocketclientdisconnect when the client disconnects (Sender:tobject;
Socket:tcustomwinsocket);
var I:integer; Begin for i:=0 to sessions do BEGIN if session[i]. CHandle =socket.sockethandle then begin session[i].
CHandle: = 0; Session[i].
cused: = False;
break;
End
End Statusbar.panels[0].
Text: = Client +socket.remotehost + has been disconnected;
End
Closes the window procedure Tfrmservermain.tbcloseclick (sender:tobject);
Begin close;
End Procedure Tfrmservermain.formcreate (Sender:tobjeCT);
Begin sessions: = 0;
End
Procedure Tfrmservermain.formclose (Sender:tobject;
var action:tcloseaction);
Begin Serversocket.close;
End
Procedure Tfrmservermain.serversocketgetsocket when the client is connecting to the server side (Sender:tobject; Socket:integer;
var clientsocket:tserverclientwinsocket); Begin Statusbar.panels[0].
Text: = client is connecting ...;
End
The client has an error procedure tfrmservermain.serversocketclienterror (sender:tobject; Socket:tcustomwinsocket;
Errorevent:terrorevent;
var errorcode:integer); Begin Statusbar.panels[0].
Text: = Client +socket.remotehost + error occurred.;
ErrorCode: = 0;
End End.</span>
· Client source code (UCLIENTMAIN.PAS):
<span style= "Font-size:12px;color: #000000;" ><span style= "FONT-SIZE:18PX;"
>unit Uclientmain; Interface uses Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, Scktcomp, Comctrls, Toolwin
, Extctrls, Stdctrls, Buttons; Const SOCKETHOST = 172.16.1.6;
Server-side Address type Tfrmclientmain = Class (Tform) Controlbar1:tcontrolbar;
Toolbar1:ttoolbar;
Tbconnected:ttoolbutton;
Tbsend:ttoolbutton;
Tbclose:ttoolbutton;
Tbdisconnected:ttoolbutton;
Clientsocket:tclientsocket;
Edit1:tedit;
Memo1:tmemo;
Statusbar:tstatusbar;
BTNSEND:TBITBTN;
Procedure Tbconnectedclick (Sender:tobject);
Procedure Tbdisconnectedclick (Sender:tobject); Procedure Clientsocketread (Sender:tobject;
Socket:tcustomwinsocket);
Procedure Tbsendclick (Sender:tobject);
Procedure Tbcloseclick (Sender:tobject);
Procedure Formshow (Sender:tobject);
Procedure Clientsocketconnect (Sender:tobject;
Socket:tcustomwinsocket); Procedure ClientsockEtconnecting (Sender:tobject;
Socket:tcustomwinsocket);
Procedure Clientsocketdisconnect (Sender:tobject;
Socket:tcustomwinsocket);
Procedure Formclose (Sender:tobject; var action:tcloseaction); Procedure Clientsocketerror (Sender:tobject;
Socket:tcustomwinsocket; Errorevent:terrorevent;
var errorcode:integer);
Private {Private declarations} public {public declarations} end;
var Frmclientmain:tfrmclientmain; Implementation {$R *.
DFM}//Open socket Connection procedure Tfrmclientmain.tbconnectedclick (sender:tobject);
Begin Clientsocket.open;
End
Close socket Connection Procedure Tfrmclientmain.tbdisconnectedclick (sender:tobject);
Begin Clientsocket.close;
End
Accept the server-side reply procedure Tfrmclientmain.clientsocketread (sender:tobject;
Socket:tcustomwinsocket);
Begin MEMO1.LINES.ADD (Socket.receivetext);
End
Send information to server-side procedure Tfrmclientmain.tbsendclick (sender:tobject);
Begin ClientSocket.Socket.SendText (Edit1.text);
End ProceDure Tfrmclientmain.tbcloseclick (Sender:tobject);
Begin close;
End
Set the server-side address procedure tfrmclientmain.formshow (Sender:tobject) to be connected;
Begin Clientsocket.host: = Sockethost;
End
Already connected to server-side procedure Tfrmclientmain.clientsocketconnect (sender:tobject;
Socket:tcustomwinsocket);
Begin tbsend.enabled: = True;
tbdisconnected.enabled: =true;
btnsend.enabled: = True; Statusbar.panels[0].
Text: = already connected to + socket.remotehost;
End
Connecting to server-side procedure tfrmclientmain.clientsocketconnecting (sender:tobject;
Socket:tcustomwinsocket); Begin Statusbar.panels[0].
Text: = connecting to server ...;
End
Procedure Tfrmclientmain.clientsocketdisconnect occurs when a connection to the server side is disconnected (sender:tobject;
Socket:tcustomwinsocket);
Begin tbsend.enabled: = False;
btnsend.enabled: = False;
tbdisconnected.enabled: = False; Statusbar.panels[0].
Text: = The connection has been disconnected with + Socket.remotehost +;
End
Procedure Tfrmclientmain.formclose (Sender:tobject;
var action:tcloseaction); BEgin Clientsocket.close;
End
Procedure Tfrmclientmain.clientsocketerror When an error occurs with the server-side connection (sender:tobject; Socket:tcustomwinsocket;
Errorevent:terrorevent;
var errorcode:integer); Begin Statusbar.panels[0].
Text: = Error with server-side connection;
ErrorCode: = 0;
End End. </span>
Summary
The above method is a simple implementation method, and it is also a relatively easy to understand method.
Through this method, the author successfully implemented the local area network multiple
The client and the server side of the socket communication function, while ensuring that a client's connection, communication or disconnection does not affect other clients
Normal communication.