1. Delphi and Socket
The computer network is composed of a series of network communication protocols, the core protocols of which are the TCP/ip and UDP protocols at the transport layer. TCP is connection-oriented, and both communicating parties maintain a path, just like the current telephone line. If you use telnet to log in to the BBS, the TCP protocol is used; UDP is connectionless, and the communicating parties do not maintain each other's status. It is used when the browser accesses the Internet. The HTTP protocol is based on the UDP protocol. Both TCP and UDP protocols are very complex, especially the TCP protocol. In order to ensure the correctness and effectiveness of network transmission, a series of complex error correction and sorting processes must be performed.
Socket is a socket specification based on transport layer protocols (mainly TCP and UDP). It was originally proposed by the University of California, Berkeley. It defines a specification for communication between two computers (also a programming specification). If two computers communicate using a "channel", then the two ends of this "channel" are two sockets. Sockets shield the differences between underlying communication software and specific operating systems, making communication possible between any two computers that have installed TCP protocol software and implemented the socket specification.
Microsoft's Windows Socket specification (winsock for short) extends Berkeley's socket specification. Using standard Socket methods, you can communicate with Sockets on any platform; using its extensions, you can implement it more effectively on Windows platforms. Communication between computers. In Delphi, the underlying Socket should also be the Windows Socket. Socket reduces the difficulty of writing communication software between computers, but in general it is still quite complicated (this will be discussed in detail later); InPRise effectively encapsulates Windows Socket in Delphi, allowing users to easily Write network communication programs. Below we explain with examples how to use Socket to write communication programs in Delphi.
2. Use Delphi to write Socket communication program.
The following is a simple Socket communication program, in which the client and server are the same program. When the client (server) enters a piece of text in memo1 and presses Enter, the text can be displayed on the server (client) ) in memo2, the reverse is also true. The specific steps are as follows:
1. Create a new form and name it arbitrarily. You might as well set it as chatForm; place a MainMenu (in the Standard column) and create ListenItem, ConnectItem, Disconnect and Exit menu items; select TServerSocket and TClientSocket from the Internet column and add them to the chatForm , where the name of TClientSocket is set to ClientSocket, Set the port to 1025, the default active is false; set the name of TServerSocket to ServerSocket, set the port to 1025, the default active is false, and leave the others unchanged; then put in two memos, one named memo1, and the other For memo2, the color of memo2 is set to gray because it is mainly used to display the other party's input. Below we explain the reason while writing code.
2. Double-click ListemItem. Write the following code:
procedure TChatForm.ListenItemClick(Sender: TObject);
begin
ListenItem.Checked := not ListenItem.Checked;
if ListenItem.Checked then
begin
ClientSocket.Active := False;
ServerSocket.Active := True;
end
else
begin
if ServerSocket.Active then
ServerSocket.Active := False;
end;
end;
The description of this program segment is as follows: When the user selects the ListemItem, the ListenItem is inverted. If selected, it means that it is in the Listen state. What readers need to understand is: listen is a proprietary method when Socket serves as the Server. If it is in listen, then ServerSocket is set to active state; otherwise, listening is canceled and ServerSocket is closed. In fact, only the user initially selects this menu item, indicating that the program is acting as a server. On the contrary, if the user selects ConnectItem, it must be used as Client.
3. Double-click ConnectItem and enter the following code.
procedure TChatForm.ConnectItemClick(Sender: TObject);
begin
if ClientSocket.Active then ClientSocket.Active := False;
if InputQuery('Computer to connect to', 'Address Name:', Server) then
if Length(Server) > 0 then
with ClientSocket do
begin
Host := Server;
Active := True;
ListenItem.Checked := False;
end;
end;
The main function of this program is to set the application as a client when the user selects the ConnectItem menu item, and an input box pops up to allow the user to enter the address of the server. This is why we do not fix the ClientSocket host at the beginning, so that users can dynamically connect to different servers. What readers need to understand is that the host address is only an attribute that Socket has when it is a client. When Socket is a server, it "generally" does not use the address because it is bound to the local machine.
4. Write the following code in the keydown method of memo1:
procedure TChatForm.Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_Return then
if IsServer then
ServerSocket.Socket.Connections[0].SendText(Memo1.Lines[Memo1.Lines.Count - 1])
else
ClientSocket.Socket.SendText(Memo1.Lines[Memo1.Lines.Count - 1]);
end;
The function of this code is obvious, that is, it starts sending messages. If it is a Server, it only sends a message to the first client. Since a server can connect to multiple clients, and each connection with the client is maintained by a Socket, the ServerSocket.Socket.Connnections array What is stored is the Socket that maintains the connection with the Client. In the standard Socket, the server-side Socket obtains the Socket that maintains the connection with the client through the return value of the accept() method, and the methods for sending and receiving messages are send(sendto) and recv(recvfrom) respectively. Delphi has done this Encapsulation.
5. A brief introduction to the remaining codes.
procedure TChatForm.ServerSocketAccept(Sender: TObject;
Socket: TCustomWinSocket);
begin
IsServer := True;
end;
The Accept method of ServerSocket is completed when the client connects for the first time. From its parameters, it can be considered that it is executed after the standard accept method. Because there is the parameter type TCustomWinSocket, it should be the return value of the standard Server-side Socket.
procedure TChatForm.ClientSocketRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo2.Lines.Add(Socket.ReceiveText);
end;
procedure TChatForm.ServerSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo2.Lines.Add(Socket.ReceiveText);
end;
These two pieces of code are triggered by Delphi when the server side and client side receive each other's messages, and their function is to display the received messages in memo2. Among them, the Socket in ClientSocketRead is actually the Socket itself, and the Socket in ServerSocketClientRead is actually a Socket in ServerSocket.Socket.Connection[]. However, in Delphi, the server-side Socket is effectively encapsulated.
procedure TChatForm.ServerSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo2.Lines.Clear;
end;
procedure TChatForm.ClientSocketDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
ListenItemClick(nil);
end;
These two paragraphs are relatively simple. Among them, ServerSocketClientConnect is triggered when ServerSocket receives a new connection. ClientSocketDisconnect is triggered when ClientSocket issues Disconncet.
procedure TChatForm.Exit1Click(Sender: TObject);
begin
ServerSocket.Close;
ClientSocket.Close;
Close;
end;
procedure TChatForm.Disconnect1Click(Sender: TObject);
begin
ClientSocket.Active := False;
ServerSocket.Active := True;
end;
The first paragraph is to close the application. In standard Socket, when each Socket is closed, the closesocket() method must be called, otherwise the system will not release resources. In ServerSockt.Close and ClientSocket.Close, the closesocket() method must be called internally in the system.
3. Standard Socket and Socket in Delphi.
The standard Socket application framework is as follows:
Server side: Socket()[Create a new Socket]--Bind()[Bind with the server address]--Listen()--Accept()--block wait--read()[Accept messages, in the windows platform , the method is send(TCP), or sendto(UDP)]--process service request--Write()[send message, in Windows platform, the method is send(TCP), Or sendto(UDP).
The client side is relatively simple: Socket()--Connect() [Connect to a specific server through a certain port, which is to establish a connection with the server]--Write()--Read().
Socket can be based on TCP or UDP, and Socket is even built on other protocols, such as IPX/SPX, DECNet, etc. When creating a new Socket, you can specify what type of Socket to create. Bind() is used to bind to the server's address. If a host has only one IP address, the role of binding is actually relatively redundant. Listen() starts to monitor the network, Accept() is used to accept the connection, and its return value is the Socket that maintains contact with the client.
In Delphi, Socket in Windows is effectively encapsulated. In Delphi, according to their inheritance relationship, they can be divided into two categories:
1. TComponent--TAbstractSocket--TCustomSocket--TCustomServerSocket--TServerSocket
TComponent--TAbstractSocket--TCustomSocket--TClientSocket
2. Inherit directly from TObject:
TObject--TCustomWinSocket--TServerWinSocket
TObject--TCustomWinSocket--TClientWinSocket
TObject--TCustomWinSocket--TServerClientWinSocket
It can be seen that the first type is based on TCustomSocket, and the second type is based on TCustomWinSocket. The first type is built on TComponet, and the second type is built directly on TObject. Therefore, if the user is very familiar with Socket and wants to write a console program, he can use the TCustomWinScoket class.
As can be seen from the same uses, they are all implemented in ScktComp.pas, and schtComp.pas contains the winsock.pas file. If you continue to delve into the winsock file, you can find all the basic methods of Windows Socket.
In fact, if you understand the standard Socket application framework, you will be comfortable using Delphi to write Socket applications; this does not mean that you must understand the standard functions in complex Socket, and it is not necessary, because Delphi has already done it for you. It is well encapsulated, which is the strength of Delphi. You only need to understand a little bit of the basic framework.
This is my understanding of Socket applications in Delphi. I hope you can correct me if I have any shortcomings. At the same time, I am also happy to answer questions about Socket in Delphi.