Use sockets version 1.0 by zyqsj
Use the Sockets Socket control to create an application that uses TCP / IP and related protocols to communicate with other systems. Using Sockets, you can read and write other machines connected through it without worrying about the details of the actual network software. Sockets provides a connection based on TCP / IP protocol. In addition to this, you can work well, in other related protocols, such as Xerox Network System (XNS), Digital's Dec Net, or Novell's IPX / SPX family. C Builder provides you write a web server or a client application to read and write other systems. A service or client program is usually focused on a single service such as Hypertext Transfer Protocol (HTTP) or File Transfer Protocol (FTP). Using Server Sockets, an application can provide one of these services to connect to a client that wants to use the service. Client Sockets allows an app to use a service application for this service using one of these services. Use Sockets to write applications, you must understand the following knowledge: 1. Services When you need to write network services or client applications, Sockets provides a joining. For many services, like HTTP or FTP, third-party service providers provide these services have been quite valid. Some even bundled with the operating system, so you can write it yourself. However, when you want more control services, if you want your application to communicate with network communications, or when there is no service to provide your special service, you may want to build your own service or customer. application. For example, when working in Distributed Data Sets, you may want to write a layer of communication with other system communications for the database. Want to use Sockets to implement a service, you must understand: 1. Service Agreement Before you write a network service or customer program, you must understand what service will be provided or used. Your web application must support the standard protocol of many services. If you are standard services such as HTTP, FTP write network applications, or Even Finger or Time, you must first understand the protocols used in communication with other system. Special Service Details You must see the documentation provided or used. If your application provides a new service to communicate with other system, the first step is to design a communication protocol for the server and client of this service. What information will be sent? How to organize this information? How do I encode this information? Application communications often, your network server or client application provides a layer of services used between network software and an application. For example, an HTTP service site provides content and answers between the Internet and a Web service application for HTTP request information. Provide an interface between Sockets between your web app (or customer application) and network software. You must provide an interface that is used in your application and intercom. You can copy the standard API provided by third-party service providers, or you can design and publish your own API. 2. Understand the service and port many standard services are associated, specified port numbers. When performing a service, you can consider a port number for your service. If you implement a standard service, Windows Socket Objects provides some ways to let you look for a port number for your service. If you provide a new service, on a Windows 95 or NT machine, you can specify a associated port number for your service in the file service. For more information on Services file, please see Microsoft's Windows Sockets documentation. Second, the Socket connection type Socket connection can be divided into three basic types, which reflects how to start connecting and local Socket connections. These three types are: 1. Client Connection Client Connections is a client Socket for a local system to connect to a server Socket on a remote system. The client connection begins by the client socket.
First, the client socket must describe the server socket it wants to connect. Then the client socket looks for the server Socket, which is required to connect when the server is found. The server Socket may not complete the correct connection. Server Sockets maintains a client request queue and completes the connection when they have time. When the server socket accepts the client connection, the server socket will send a complete description to the client Socket it wants to connect, and the client's connection is complete. 2. Listening to the connection server Socket does not locate the client, instead, they form a passive, "semi-connected" state, listen to the request from the client. The server sockets form a queue that stores the connection requests they have heard. This queue records the client connection request as they have been connected. When the server Sockets agrees that the client connection request, it forms a new Socket to connect to the client, so this listening connection can keep the open state to allow other client requests. 3. Server connection When listening to the Socket agrees a client request, the server side Socket forms a server connection. When the server is agreed to connect, send a server Socket description to the client to complete the connection. This connection is confirmed when the client socket receives this description. One but connected to the client's socket, the server connection cannot recognize the connection from one client. The same capabilities have the same capabilities to receive the same event type. Only the listening connection is different, it has only one single end. Third, Sockets Description Sockets makes your web application communicates with other systems over the network. Each Socket can be seen as a terminal point in the network connection. It has a specified address. * This system is running * The interface type it understands * The port used to connect to a complete Socket connection description, you must provide the address on both ends of the connection. Before you start a socket connection, you must complete the connection you want to get. Some information can be obtained from a system platform that is running in your application. For example, you don't need to describe a local IP address of a client Socket - this information can be obtained from the operating system. You must provide information about the type of Socket that you work. Client Socket must describe the servers they want to connect. Listening Server Sockets must describe the ports they provide a reactive server. A full description of a socket connection terminal includes two parts: 1. IP address host is such a system, which runs an application containing socket. You must describe the host to the Socket, complete this description by giving the IP address of the host. The IP address is a string with four numbers (Byte) values, in standard Internet dot paid. For example, 123.197.1.2 A simple system can support more than one IP address. IP addresses are often difficult to memorize and are easy to get wrong. A alive method is to use the host name. The host name is an alias of the IP address, which is the unified resource positioning (URLS) you often see. It is a string, including domain names and services. For example http://www.wsite.com Many internal networks are provided to the host's name, the system IP address is an Internetip address. On the Windows95 and NT machines, if a host name cannot be used, you can create an entry name for your local IP address (this local IP address should refer to the host IP address you want to connect "in the hosts file. . For more information on HOSTS file, please see the documentation of Windows Sockets. Server Sockets does not need to specify hosts. The local IP address can be read from the system. If the local system supports more than one IP address, the server Sockets will listen to the client request on all IP addresses. When a server Socket consents a connection, the client provides a remote IP address.
Customer Sockets must specify the remote host by providing hostname or IP address. As a host name and IP address, a number of applications use a host name to specify a system. The host name is easy to remember and easy to check the typesetting error. Further, the server can change the system or the special host name associated with the IP address. Using a host name, you can allow the client to describe the abstract site by the host name, even if the host uses a new IP address. If the host name is unknown, the customer socket must specify the IP address used by the server system. By giving an IP address to specify the server faster. When you provide a host name, Socket must search for IP addresses related to this hostname before locating the server system. 2. Although the port number provides enough information to find enough information in the Socket connection, you usually need to specify the port number of that system. Without a port number, a system can only perform a single connection at the same time. The port number is the unique identifier that allows a standalone system to connect to a host that supports multiple connections at the same time, each connection must specify a port number. In web applications, the port number is a digital code for the server tool. There is a habit to listen to the client connected to their own fixed port numbers so that they can find the client sockets. Server Socket listens to the relevant port numbers for them. When they allow a client Socket connection, they create a separate socket connection that uses different dedicated port numbers. Through this method, you can continue to listen to the port number of the relevant service. Client Socket uses a dedicated local port number without other sockets to find them. They specify the port number of the server-side Socket they want to connect so they can find the server application. Often, this port number is indirectly specified by named service you want to connect. Fourth, use the Socket control C Builder to provide two socket controls, client sockets, and servers sockets. They allow your network application to connect to other machines and allow you to read and write information through this connection. Associated with each Socket control is a Windows Socket object, and their role of the terminal is an actual Socket connection. The Socket control uses the Windows Socket object to encapsulate the Windows Socket API call, so your application does not have to care about the details of the connection or manage Socket information. If you want to use the Windows Socket API call or custom connection details, the Socket control provides convenience, you can use the Properies, Events, and methods of the Windows Socket object. 1. Add a client Socket to your Form or Data Module to make your application a TCP / IP customer. Customer Sockets allows you to specify the server Socket you want to connect to and the services you want the server. One, you describe what you want, you can use the customer's Socket control to complete the connection service. Each customer Socket control uses a separate customer Windows Socket object to deck the client terminal in the connection. Use the customer sockets to go: A. Specify that the you want to get the customer's Socket control has a digital Properties, allowing you to specify the server system and port you want to connect. You can specify the server system through the host name and use Host Property. If you don't know the host name, or if you care about find the speed of the server, you can specify the IP address of the server system, by using Address Property. You must specify one of the IP addresses and host names. If you are all specified, the customer's Socket control will use the host name. In addition to the server system, you must specify your customer socket to connect the port on the server system. You can use Port Property directly to specify the service port number.
Or use the name you want to get directly in Service Property. If you specify port numbers and service names, the customer's Socket control will use the service name. B. Establish a connection Once you have completed the setting description description you want to connect to the properties of the server you want to connect, you can connect, by calling the OPEN method. If you want to automatically establish a connection when your application is started, set Active Property to TRUE when designing, and sets with Object Inspector. C. After obtaining information about the connection to the server Socket, you can use the customer Windows socket object related to your customers' Socket control to obtain information about the connection. Use Socket Property to access Client Windows Socket Object. Windows Socket Object has a Properties that allows you to determine the address and port number used by the clients and servers connected to the connected. When using a Windows Socket API called, you can use the SocketHandle Property area to get the Handle used by the Socket connection. You can use the Handle Property to access Windows to receive information from the socket connection. AsyncStyles property determines which information type is Windows Handle to be received. D. Close connection When you complete the communication want to close the socket connection, you can close the connection by calling the Close method. The connection may be turned off by the server. If this is this, you will receive a notification of an OnDisconnect event. 2. Add a server Sockets to your Form or Data Module to make your application a TCP / IP server. Server Sockets allows you to specify the service you want or you want to use to listen to the client request. You can use the server Socket control to listen and allow customer connection requests. Each server Socket control uses a single server Windows Socket Object (TSERVERWInsocket) to answer the connection in the server side. It usually uses a server customer WinODWS Socket Object (TSERVERCLIENTWINSOCKET) to answer each activity of the server and connect to the client Socket that is allowed. Use the server sockets to go: A. Specify port before you can listen to the customer request, you must specify a port to your listening service. You can use Port Property to specify this port. If your server application provides a standard service, this service uses a associated port associated with use. You can specify port numbers directly using Service Property. Using Service Property is a good idea to reduce errors when setting port numbers. If you specify both Port Property, you specify Service Property, and the service name will use the service name. B. Listening Customer Request Once you set your port number on the Server Socket control, you can listen to a connection by calling the Open method at runtime. If you want your application to automatically listen to the connection during startup, set the Active property to True by using the Object Inspector when designing. C. Connect to the client. They will automatically accept this request when the listening service Socket control receives a client connection request. The ONCLIENTCONNETC event will happen when you have received the notice. D. Get information about the connection one but your server socket opens the listening connection, you can use the server Windows socket Object associated with your server Socket control to obtain information about the connection.
Use Socket Property to access Server Windows Socket Object.Windows Socket Object There is a property that allows you to find a customer socket connection to all active Customer Socket is allowed to be connected by the server Socket control. Use the Handle property to access the information received through the socket connection through the Socket. Each activity is connected to the customer app, and the customer Windows Socket Bject (TSERVERCLIENTWInsocket) is packaged. You can access all of these through the connection properties of Server Windows Socket Object. These Server Client Windows Socket Object Some properties allow you to decide which addresses and port numbers are used on both ends of the connection - Customer and Server Socket. When you use the Windows Socket API call, you can use the socketHandle property to get the Handle used for the Socket connection. You can use the Handle property to access the information from the Socket connection from the socket connection. The asyncStyles property determines which type of information will be received by Windows Handle. E. Close connection When you decide to turn off the listening connection, call the Close method. This will turn off all open, connect to the client application, and cancel any unconnected connection, then close the listening connection so that your service Socket control is not accepted any new connection. When the client closes their own independent connection to your Server Socket connection, you can get a message in the OnClientDisconnect event. V. Advocates for Socket events When using sockets write an application,
Most of the work happens in the Handler event of the socket control. When you start reading or writing through the socket connection, OnRead and OnWrite events happen to notify Sockets in Non-Blocking Client Sockets. Similarly, Server Sockets (Blocking or Non-Blocking) Received ONCLIENTREAD and ONCLIENTWRITE events. When the server ends a connection, the customer ScokeTs receives an OnDisconnect event. When the client ends a connection, the server socket receives an OnClientDisconnect event. In addition, the client sockets and server-side socket are from the connection When you receive an error message, there will be an error event. Error event: Customer Sockets and Server Sockets typically generate an onERROR event when they receive an error message from the connection. You can write an onError event handling To respond to these error messages. This OneRror event handles provides information about this error when the socket is trying to do, and the error code provided by the error message. You can respond to this error in the OneRror event processing, and put the error code Change to 0 to avoid Socket production. When starting and completion occurs, the Socket control usually receives an event number. If your application needs to change the process of the Socket start operation or start through the connection When you read or write, you will write event handlers to answer these client events and server events. A.Client events When a customer socket opens a connection, the following events occur: 1. A ONLOOKUP event first occurs, it tries to position Server Socket. You cannot change Host, Address, Port, Service properties to change the server you want to locate. You can use the socket property to access the Client Windows Socket Object, and use its socketHandle property to call the Windows API to change Socket Customer properties. For example, if you want to set a port number in the customer application, you must do this before the Server Client connection. 2.Windows socket settings and initialization event notifications. 3. When you find a Server Socket, a OnConnecting event In this incident, Windows Socket Object can utilize some information about the service socket on the other end of the connection through the socket property. This is the first opportunity to get the port and IP address of the actual use, which may differ from the monitor Socket The port or IP address is obtained. 4. The server agrees to the request, the client socket complete the connection. 5. When a connection is determined, an OnConnect event occurs. If your socket immediately begins to read or write through the connection, you should write A OnConnect event handler is asking for this matter. B. Server events Server Socket Controls Connects to both: listen to the connection and connect to the customer application. Server Socket receives all events of these two connections. Listening Event When the monitor connection is constituted, the OnListen event happens. At this time you can get Server Windows socket object through the socket attribute. You can use its socketHandle property to change the socket, before the Socket opens the monitor. For example, if you want to limit the listening service Use the IP address, you can do this on this OnListen event handler. Events connected to the client When a server Socket agrees to a client connection request, the next event happens:
1. Server Socket generates an OnGetSocket event, which is transmitted to the other end of the connection via Windows Socket Handle. If you want to provide yourself defined TSerClientWinsocket of Descendant, you can build in the OnGetSocket Event Handler, will be used to replace TSERVERCLIENTWISOCKET. 2 A onaccept event happens, transmit a new TServerClientWinsocket object to the event handle. This is the first point, when you use the TServerClientWinsocket attribute to get the information of the client that is connected to the client. 3. If the service type is stthreadblocking, An ONGETTHREAD event happens. If you want to provide your own TServerClientThread subclass, you can build one in the OnGetThread event handle, which will replace TSERVERCLIENTTHREAD. 4. If the service type is StthreadBlocking, an ONTHREADStart event occurs when this thread begins When executed. If you want to perform any initialization this thread, or call some Windows Socket API, you should use the ONTHREADSTART event handle before which the thread begins to read and write. 5. When the client completes a connection, an OnClientConnect event occurs. If it is a non-blocking service, you may want to start reading or writing at this end via the socket. Six, reading and writing through the socket connection to other machines Through these connections to read and write information What information is what you want to read and write, or when you want to read and write, it relies on which Socket connection related services. Reading and writing via Sockets can be asynchronous, so you don't need to block in your web application. Other code execution. This is called Non-Blocking Connection. You can also pass through the Blocking Connection, at this time your next line of code must wait until the read or write operation is completed. A.non-blocking connection, read and write are asynchronous So do not need to block other code execution in your network application. Create a non-blocking connection: 1. Set the clientType property in the customer socket to ctnonblocking. 2. Set the serverType property in ServerType property in ServerType properties for Stnonb When the connection is non-blocking, the other end of the connection is attempting to read or write the read and write event to inform you of your socket. Read and write operation event Non-blocking sockets wants to read or write, it A read and write operation event will notify you Socket. On the client sockets, you can respond to these events in the OnRead or OnWrite event handle. On the server-side ScokeTs, you can in the onClientRead or OnClientWrite event handle to these events Make a reaction. Windows socket object associated with the socket connection is used as a parameter in the read or write of the event handle. Windows socket object provides a method number (Number of Methods) to allow you to read or write. Via Socket Connection read, use the ReceiveBuf or ReceiveText method. Before using the ReceiveBuf method, use the Recereength method to determine the number of bytes that the connection to the other end Socket is ready to send. Write through the socket, use SendBuf, SendStream, or Sendtext Method. If you send a Socket connection after sending information via Socket, you can use the SendStreamThendrop method. SendStreamThendrop method will close the socket connection after all the information is written, it can read the information from Stream. If you use SendStream or SendStreamThendrop method, do not release Stream Object, Socket will automatically release this stream after the connection is over. Note:
SendStreamThendrop will close a separate customer connection service instead of listening. B.Blocking Connections When you use the connection is blocking, your socket must be read or write through the connection, better waiting from the Socket connection. Notice. Use the Blocking Socket when your connection end read and write operation changes. For the client sockets, set the clientType property to ctblocking to make it to form a blocing connection. According to your client application, you may want to build. An execution thread to complete the read or write operation so that your application can continue to perform other threads, when it is waiting to be done by the connection or write operation. For the server sockets, set the serverType property as stthreadblocking to make a blocking connection. Because Blocking Connections hangs the execution of other code while waiting for the connection or write information, the server Socket control typically generates a new execution thread to each client connection, when Servertype is set to stthreadblocking. Many applications using Blocking connection Write using threads (Using Threads. Even if you don't use thread, you may also want to use TWinsocketStream to read and write. 1) Using threads When using a blocking connection to read or write, customer sockets will not automatically generate A new thread. If your client application does not do, until the read or write information is completed, then this is what you want. If your app includes a user interface, it also needs to respond to the user's operation, then You may want to generate a separate thread to read and write. When the server sockets forms a blocking connection, they often generate separate threads to each client, so no customers need to wait until other customers complete through the connection or write. By default, server Sockets uses TServerClientThread objects to perform different threads for each connection. TSERVERCLIENTTHREAD object simulates OnClientRead and OnClientWrite events in the non-blocking connection. However, when listening to Socket, not local Thread-local. If the customer requests frequent, you will want to build your own TSERVERCLIENT Thread subclasses provide a secure thread-safe to complete read and write. When writing a client thread or writing a server thread, you can use TwinsocketStream to do actual read and write operations. A) Write the client thread to customers End Connection Write a thread to define a new thread object, use the new thread object dialog. Your new thread object execute method's handle of the handle of the read / write operation, you can create a TwinsocketStream object, then use it to read Or write. Use your own thread to create it in the OnConnect event handle. For more information on establishing and running the thread, see Executing Thread Objects. Example: This example shows a client thread to the server after the connection is determined. write request void __fastcall TMyClientThread :: Execute () {while // make sure connection is active {try {TWinSocketStream * pStream = new TWinSocketStream (ClientSocket1.Socket, 60000). (Terminated && ClientSocket1-> Active!); try {char buffer [10]; GetNextRequest (buffer); // GetNextRequest Must Be a thread-save method // Write a Request to the Server Pstream-> Write (Buffer, Strlen (Buffer) 1);
// continue the communication (eg read a response)} __finally {delete pStream;}} catch (Exception & E) {if (E.ClassNameIs ( "EAbort")!) Synchronize (HandleThreadException ()); // you must write HandleThreadException }}} B) write server-threaded server connection thread is derived from TServerClientThread because of this, you can not use a new thread Object dialog box alternative to manually declare your thread as follows:.. class PACKAGE TMyServerThread: public ScktComp :: TServerClientThread {public void __fastcall ClientExecute (void); Note that you will replace the Execute method with the overloaded clientExcute method. Execute the ClientExecute method to write a similar Execute method thread to the client. However, when you put a customer's Socket control to your application from the control bar When you come to replace this method. Listening Services Socket As a connection, the service customer thread must be built using the TServerClientWinsocket object. This can utilize a common cientsocket property. In addition, you can use the HandleException this protected method, better than you Write your Thread-Safe Exception. WARNING: Server Sockets caches the thread they use. Confident that the ClientExecute method performs some necessary initialization operations so that they do not produce unfavorable results when executing. When you use you When thread, create it in the ONGETTHREAD event handle. When the thread is established, set the createSuspended parameter to false. Example: This example shows a thread for an application service, this application is a read request by the client after the connection is determined. Void __fastcall tmyserverthread :: ClientExecute () {While (! Terminated && ClientSocket-> Connected) // make sureness is active {try { TWinSocketStream * pStream = new TWinSocketStream (ClientSocket, 60000); try {char buffer [10]; memset (buffer, 0, sizeof (buffer)); if (pStream-> WaitForData (60000)) // give the client 60 seconds to Start Writing {IF (Buffer, Sizeof (Buffer) == 0) ClientSocket-> Close (); // if can't read in 60 seconds, close the connection // Now process the request} else ClientSocket -> close ();} __finally} catch (...); {handleexception ();