BCB master advancement (eight) TSERVERSOCKET and TCLIENTSOCKET application skills
: nxyc_twz@163.com
In network programming, Winsocket API programming is the most basic and the most lockable part. However, if you use C Builder 5 as a programming platform, things become more simple! Through my introduction, I believe that you will be able to quickly grasp the design and techniques of the design based on the C / S system. In BCB, TSERVERSOCKET and TCLIENTSocket cover basic Winsocket programming, where tServersocket is used as server side, and TclientSocket is used as client, and the two components do not provide Socket connections, but they have a socket property, this property is provided Socket connection. Let's introduce you to the methods of the two components, and then take a look at the use of the two components through an example. 1) TSERVERSOCKET Name Type Description Socket TServerwInsocket The most important properties, providing socket connections, in fact, send / receive data to rely on this property .port Int To listen to ports, if the service type is specified in the service property, this property will be Ignore. Service Ansistring, such as HTTP, FTP, etc. If the service type is specified here, Port will be ignored because various services have specific ports, such as ftp: 21, http: 80Servertype TSERTYPE settings and customers The way, the value is two enumerations of ordinary stnonblocking and stthreadblocking, Stnonblocking indicates that each customer is handled in a separate thread with a non-blocking manner. And use OnClientRead () and OnClientWrite () to notify the server-side Socker's Socker to read and write. StthreadBlocking means that the client is connected in a blocking method, which is available in a way the initiative. Active Bool Activation Services is equivalent to calling an OPEN () method. OnClientRead event notifies the server to read the information when there is a client request connection. OnClientWrite is similar to this. 2) TClientSocket Name Type Description Socket TClientWinSocket same with TServerSocketActive bool IP address TServerSocketAddress AnsiString server, such as server connection 202.98.35.14ClientType TClientType, enumeration constant value of two ctNonBlocking, tBlocking. CTnonBlocking represents non-blocking methods, ctblocking represents a blocked method, see the above example.
Host Ansistring The host name to connect, such as www.cpcw.comport Int with TSERVERSOCKETSERVICE ANSISISTRING Tiennecting, onConnecting, OnDisconnect, onConnecting, OnDisconnect, inform the client to read the information. OnWrite is similar to this. TSERVERSOCKET and TCLIENTSOCKET provide only basic server / client connections, which truly provides data transfer. It is the property socket, which is TSERVERWInsocket and TclientWinsocket, and the parent class of TSERVERWInsocket and TclientWinsocket is TCUStomwinsocket, let's Let's take a look at the TSERVERWInsocket and TclientWinsocket commonly used properties and methods. Common Properties Method (Sourceful from TCUSTomWinsocket) Name Type Description Connected Bool Checks whether to connect to success Localaddress Ansistring local IP address, similar to Localhost: Native domain name, localport: Native port Remoteaddress Ansistring the IP address of the other end, similar to Remotehost : The other end domain name, Remoteport: The other end port socketHenTle INT read-only, returns the Windows handle of the socket object, calling the Winsocket API function to use it. The Handle HWnd Socket can be accepted by the asynchronous events in the form of a Windows message to this handle. The close () method is used as a server, closes all connections; as a client, turn off your own connection Sendtext (ANSISTRING) method to the server, send a string, sendbuf (void * buff, int count) Send the COUNT bytes in the buffer buff , Return the number of bytes sent by the actual sent SendStream (TSTREAM * ASTREAM) sends a stream to the socket. ReceiveText () reads and returns a string from the Socket. ReceiveLength () reads how many bytes of bytes required for data from Socket. ReceiveBuf (void * buff, int count) reads the data of count bytes from the socket to the buff. TclientWinsocketTClientWinsocket only adds a ClientType property to determine the connection type with the server (see TclientSocket-> ClientType). TSERVERWINSOCKET Name Type Description Servertype service type, see TSERVERSOCKET-> Servertype. ActiveConnection INT reads read, returns the number of connections to the current activity. Connection TCustomWinsocket array, index n represents N 1 connection, such as Connection [0] represents the first connection. With these knowledge, we can complete some basic Winsocket programming. Here, take a simple chat program to see the specific application.
First place the following VCL components on the form, and modify the corresponding attribute: Type Name property CAPTION / TEXT Description Tcheckbox CKListen Listening When elective The name used. TbitBTN BBTSAVE & S Save Click to save the conversation Content Tbitbtn BBTClose & c Turn off this window (Settings Kind = BKClose) Tedit EDTALK This input Content TMEMO MMTALK This Display Content TSERVERSOT ServerSocket1 is used as a server (set port = 2222) TclientSocket ClientSocket1 uses (setting port = 2222) TsaveDialog Sdtalk saves files as customers (setting defaultext = "*. Txt", filter = text file (* .txt) | * .txt | All files (*. *) | *. *). TSTATUSBAR STATUSBAR1 is used to display some prompt information, as long as you add a column in the attribute "Pannels" as a server setting: When you click "Listening", if you don't listen, you will start listening, you will start listening, and "monitor" in the prompt bar. And invalidate the "connection" check box. If you have already listened, cancel the listening and make the "Connect" check box valid.
So, add the following code in CKLISTEN's OnClick event: if (Serversocket1-> Active) {ServerSocket1-> Active = false; cklisten-> checked = false; statusbar1-> panels-> items [0] -> text = "" } else {serversocket1-> active = true; cklisten-> checked = true; clientsocket1-> active = false; statusbar1-> panels-> items [0] -> text = "listening ...";} ckconnect-> Enabled =! (CKLISTEN-> Checked); When there is a customer joining, a notification is issued to all customers: and add this message in the own MMTalk: So the following code is added to the OnCept event of ServerSocket1: int i; Ansistring str1 = " Server message: " Socket-> RemoteHost " Add "; for (i = 0; i
Therefore, adding OnClick event ckConnect the following code: if (ClientSocket1-> Active) {ClientSocket1-> Active = false; ckConnect-> Checked = false;} else {AnsiString Server = "localhost"; if (InputQuery ( "connection "," Please enter the host address you want to connect: ", server) {ClientSocket1-> host = server; clientsocket1-> active = true; ckconnect-> checked = true;}} cklisten-> enabled =! (Ckconnect-> Checked; when the connection server is successful, display this information in the status bar, so add: statusbar1-> panels-> items [0] -> text = "connected to the host:" Socket-> Remotehost; When the server sends a string, add it in mmtalk, but if this string is sent by the self (because the server will send the received message to each customer), the information is repeated, so, To compare whether the last two information in mmtalk is the same, if the same, delete the duplicate information. The code is as follows: mmtalk-> lines-> add (socket-> receivetext ()); int i = mmtalk-> lines-> count-1; if (mmtalk-> lines-> strings [i] == mmtalk-> Lines -> Strings [i-1]) mmtalk-> lines-> delete (i); public part When the conversation content is input in Edtalk, press Enter to indicate the input completion, simply send the conversation content and clear the contents of EDTalk. When sending information, you want to see the program as a server or a client, if the server sends information to each customer; if it is a customer, the information is sent to the server. The code is as follows: if (key == 13) {mmtalk-> lines-> add (edname-> text ":" edtalk-> text); if (cklisten-> enabled && ckconnect-> enabled == false) // "listens "Valid," connection "is invalid.