We are writing a chat on delphi. We write our own ICQ chat in Delphi. Writing your ved bike in Delphi


I think you have had the idea to create your own (corporate) chat more than once. The same idea came to me, and, as always, I began to search for information on the Internet, but I didn’t find anything good. Everything somehow does not fully describe how this can be done.

And I promised myself how I would study so I would lay out the full information on this topic. I was doing my chat on sockets. They can communicate both over the Internet and over a local network. To do this, you just need to know the IP address. Programmed in Delphi7.

Installing the required components

Since I did on delphi7, there were no default components that I needed. ( ServerSocket1, ClientSocket1).
To do this, you need to add Socket components.

Go to the menu Component -> Install Packages ... -> Add -> dclsockets70.bpl

And we indicate the path to the package with components, it is located in the Delphi root folder in the Bin package. I had it in:

C: \ Program Files \ Borland \ Delphi7 \ Bin \ dclsockets70.bpl

After this addition, these components should appear in the Internet tab.

Component placement and coding

I threw the following elements onto the form: ServerSocket1, ClientSocket1, Edit1 (for chat), Edit2 (for server IP address), Memo1 to display a message, and 3 buttons.

To create a Server, write the following thing to the event in the button:

function GetLocalIP: String;
const WSVer = $ 101;
var
wsaData: TWSAData;
P: PHostEnt;
Buf: array of Char;
begin
Result: = "";
if WSAStartup (WSVer, wsaData) = 0 then begin
if GetHostName (@Buf, 128) = 0 then begin
P: = GetHostByName (@Buf);
if P<> nil then
Result: = iNet_ntoa (PInAddr (p ^ .h_addr_list ^) ^);
end;
WSACleanup;
end;
end;

procedure TForm1.Button3Click (Sender: TObject);
begin
ServerSocket1.Port: = 65000; // Port of your server, set any one you like
ServerSocket1.Active: = True; // activate the server
ServerSocket1.Open; // run
ShowMessage ("Your IP:" + GetLocalIP); // give out our IP address so that the client can connect to us
end;

After the server has been powered on, the client will be able to connect to the server.
To do this, he writes the IP address of the server in Edit2, and clicks the connect button:

procedure TForm1.Button2Click (Sender: TObject);
begin
ClientSocket1.Address: = Edit2.Text; // server IP address
ClientSocket1.Port: = 65000; // its port
ClientSocket1.Active: = True; // activate the client
ClientSocket1.Open; // run
end;

Attention: The Client can only send a message, and the Server, in turn, can receive. For two-way communication, enable the Client and Server on two programs on the opposite end of the network.

To read the message, the server has a wait for the message to be received ... here it is

procedure TForm1.ServerSocket1ClientRead (Sender: TObject;
Socket: TCustomWinSocket);
begin
memo1.Lines.add (Socket.RemoteAddress + ":");
memo1.Lines.add (Socket.ReceiveText);
StatusBar1.Panels.Items.Text: = Socket.RemoteAddress;
end;

To send a message, I wrote in two procedures. Here they are:

procedure TForm1.SendMes (Text: String);
begin
if form1.ServerSocket1.Active then
if form1.ServerSocket1.Socket.ActiveConnections> 0 then
form1.ServerSocket1.Socket.Connections.SendText (Text);

if form1.ClientSocket1.Active then
form1.ClientSocket1.Socket.SendText (Text);
end; procedure TForm1.Button1Click (Sender: TObject);
begin
SendMes (Edit1.Text);
memo1.Lines.add (GetLocalIP + ":");
memo1.Lines.add (Edit1.Text);
end;

In this thread, I would like to write in detail how to create your simplest ICQ chat in Delphi!

What we need for this:
1.Delphi (best to use 7)
2.Installed TICQ component.
3. Straight arms.

Let's get started!
And so we create a new project in Delphi and throw the TICQ component onto the form.
we throw on the form Memo1, EDit1, Edit2, button1, ListBox1, L istBox2.
Explanation:
Memo1 - chat log
Edit1 - UIN
Edit2 - password
button1 - connection
ListBox1 - online user
ListBox2 - reg user

Button1:

Procedure TForm1.Button1Click (Sender: TObject); begin ICQClient1.UIN: = StrToInt (Edit1.Text); ICQClient1.Password: = Edit2.Text; icqclient1.Login (); end;

The ICQClient1MessageRecv1 event should look like this:

Procedure TForm1.ICQClient1MessageRecv1 (Sender: TObject; Msg, UIN: String); begin Memo1.Lines.Add (trim (nick (UIN)) + ":" + Msg); // log if Msg<>"!" then // if the message starts with "!" do not throw into the chat begin if OnLine (UIN)<>-1 then // check if the user is in the chat Send (Msg, UIN) // if in the chat it accepts messages in the chat else if Reged (UIN) = - 1 then // check for registration icqclient1.SendMessage (StrToInt (UIN), "welcome to the chat!" + # 13 # 10 + "to register, enter! reg<ваш ник>") else begin icqclient1.SendMessage (StrToInt (UIN)," To enter the chat, use the command! chat "+ # 13 # 10 +" Send help for help! ") // user is not chatting! end; end else Command ( UIN, Msg); // chat commands! End;

OnLine function:

Function TForm1.OnLine (UIN: string): integer; var i: integer; begin OnLine: = - 1; for i: = 0 to ListBox1.Items.Count-1 do if Trim (Copy (ListBox1.Items [i], 4,9)) = UIN then // length of the win OnLine: = i; end;

Sending messages to chat:

Procedure TForm1.Send (Msg, UIN: string); var i2: integer; i: integer; Str, Str2: string; begin Str2: = ListBox1.Items; for i: = 0 to ListBox1.Items.Count-1 do begin if i2 = 5 then begin Sleep (2000); i2: = 0; end; if OnLine (UIN)<>i then begin i2: = i2 + 1; Str: = ListBox1.Items [i]; if Trim (Copy (Str, 1,2)) = Trim (Copy (Str2,1,2)) then icqclient1.SendMessage (StrToInt (Copy (ListBox1.Items [i], 4.9)), nick (UIN) + ":" + Msg); end; end; end;

Nick function:

Function TForm1.nick (UIN: string): string; begin if Reged (UIN)<>-1 then nick: = TRIM (Copy (ListBox2.Items, 13,50)) end

Reged function:

Function TForm1.Reged (UIN: string): integer; var i: integer; begin Reged: = - 1; for i: = 0 to ListBox2.Items.Count-1 do if Copy (ListBox2.Items [i], 4,9) = UIN then Reged: = i; end;

And finally the Command procedure (chat commands):

Procedure TForm1.Command (UIN, Msg: string); var i, i1, razdel: integer; command, key, key2: string; Str: string; help: TStrings; begin try razdel: = 0; for i: = 1 to Length (Msg) do begin help: = TStringList.Create; help.LoadFromFile ("command / help.txt"); // Open a file with text if (Msg [i] = "") and (razdel = 0) then razdel: = i; end; if razdel<>0 then begin command: = Copy (Msg, 1, razdel-1); key: = Copy (Msg, razdel + 1, Length (Msg)); key2: = Copy (Msg, razdel + 1, Length (Msg)); end else begin command: = Msg; key: = ""; end; if (command = "! chat") or (command = "! chat") then begin ListBox1.Items.Append (ListBox2.Items); icqclient1.SendMessage (StrToInt (UIN), "you're signed in"); end; if (command = "! help") or (command = "! help") then begin if OnLine (UIN)<>-1 then begin icqclient1.SendMessage (StrToInt (UIN), help.Text); end else icqclient1.SendMessage (StrToInt (UIN), "Enter the chat to use the commands!"); end; // end; if (command = "! Exit") or (command = "! Exit") or (command = "! EXIT") then begin ListBox1.Items.Delete (OnLine (UIN)); end; if (command = "! reg") or (command = "! nickname") or (command = "! reg") and (key<>"") then begin if Reged (UIN)<>-1 then icqclient1.SendMessage (StrToInt (UIN), "You are already registered in the chat! :)") else if (Length (Trim (key))> 15) then icqclient1.SendMessage (StrToInt (UIN), "Nickname too long , It must be longer than 3 and less than 15 characters, must not contain spaces ") else if (Length (Trim (key))<3) then icqclient1.SendMessage(StrToInt(UIN), "Слишком короткий ник, Он должен быть длинной,больше 3 и менее 15 символов, не должен сожержать пробелов") else //if (Length(Trim(UIN))<9) then //icqclient1.SendMessage(StrToInt(UIN), "Ваш уин не подходит для регистрации!") //else begin ListBox2.Items.Append("0 "+UIN+" "+Trim(Key)); icqclient1.SendMessage(StrToInt(UIN), "Вы успешно зарегистрировались!Для входа в чат наберите!чат"); ListBox2.Items.SaveToFile("user/user.txt"); end; end; //end; except end; end;

Some of the readers, looking at the title of the section, may be indignant and ask: "What is the connection between X-Coding and a simple chat?" In principle, there is no connection. Chat is a simple web-based program. I know that you cannot sum everything up with one size fits all, and if some utility uses the network, it does not mean that it is hacker. But still, I will describe the creation of a chat here, because we will build it on a fundamentally different protocol than usual. In any case, this knowledge will not be superfluous.

But we'll talk about chat a little later, and now a little theory.

At the moment there are two main protocols: TCP and UDP. Previously, IPX was still very common, which was used by Novell. But at the moment he is moving away, and you rarely see such a beast. Only on older systems can you see IPX. Most of the other protocols that you know (FTP, HTTP, POP3, SMTP and so on) run on top of TCP or UDP.

What does it mean: "over another protocol"? TCP implements the basic functions for working with the network. He knows how to establish a connection with a remote computer, transmit and receive data, check the correctness of the server receiving the sent packets. Let's say we want to create a file transfer protocol (FTP). To do this, we take TCP, endow it with the capabilities we need and - get it, sign it. So it turns out that FTP works over (over) the TCP protocol. If we want to create FTP from scratch, we will have to reimplement the connection and data transfer functions. Otherwise, you just need to prepare the data in a special format (FTP protocol) and give it to the TCP protocol, which itself will establish a connection and give this data where necessary.

If you are familiar with Delphi firsthand and have a little understanding of the theory of OOP, then you have already noticed the analogy with object-oriented programming. This is how the network works. The whole thing is standardized, and if you want to learn more, then read some documentation about the OSI (Open Systems Interconnection) model and its seven levels (here again I can send it to my site or see section 4.1 of this book). This topic is quite interesting, and in any case, it is advisable to know the structure of the protocols.

UDP is very similar to TCP. It also implements data transfer capabilities, but it does not establish connections and does not maintain the integrity of the transmitted data. The protocol simply opens a port, throws a portion of data there and does not even worry about whether it has reached the recipient or not. Therefore, UDP is much faster than TCP.

If you want to work with this protocol, then you will have to implement the verification of the correctness of receiving data yourself. Therefore, for transferring files or other large-sized information, you should choose TCP, because if even one small piece of the file is lost, then it will no longer be recoverable. Well, for the chat that we will write today, UDP would be a more convenient option. It is very fast and very efficient for small message sizes.

In Delphi, the library is well suited for working with

I think she will soon be your best friend.

With the theory over, let's move on to writing a chat. Warm your fingers, mouse, keyboard and start Delphi. Now we will start my favorite pastime - programming. We need 3 components on the form.

□ Tmeto component. It can be stretched to nearly its entire shape.

□ The TEdit component into which we will write the sent message.

□ TButton button, when pressed, the message will be sent. In fig. 4.21 shows the form of the future chat.

To work with ports, we need the idUDPClient components (can send data, Fig. 4.22) from the Indy Clients tab and idUDPServer (can receive data, Fig. 4.23) from the My Servers tab. Drag one such component onto the form.

Rice, 4.22. IdUDPCiient Component Properties

Rice. 4.23. IdUDPServer component properties

Now we need to configure the protocol and OR. The first thing we will do is select any port from 1 to 65,000 through which communication will take place. I decided to choose 11245 (you can choose any other). Assign this value to the Port property of the idUDpc lient component and the De fault Port property of the idUDPServer component. This will force the client and server to run on the same port, which is necessary for the communication to work.

REMEMBER !!! UDP ports do not overlap with TCP ports. This means that TCP port 80 is not equal to UDP port 80.

Now the client (idüDPCilent) needs to specify the Host property. This is where the IP address of the computer to which messages will be sent is recorded. But our chat and messages should be received by all users in the grid who launched the program. Therefore, in order to avoid problems, it is advisable to set BroadcastEnabled equal to true for both components of ZHYTVE. A Instead of a specific IP address, use a broadcast address (the one that everyone gets). If your grid uses addresses like 192,168,100.x, then for you the broadcast address will be 192.168.100.255 (we change the last octet to 255).

Preparation is over, you can program it.

Create a button event handler and write the following code there:

Procedure TForml.ButtonlClick (Sender: TObject); begin IdUDPClientl.Send (Editl.Text); end;

There is only one line here, which sends the contents of the input line (of the component

Now we need to teach the UDP server to receive this information. To do this, create an OnUDPRead event handler for the idUDPServer component. In it, write the following:

Procedure TForml. IdODPServerlüDPRead (Sender: TObject; ÄEata: TStream; ABrnding: TIdSocketHandle);

var StringFormatedStream: TStringStream; s: String; begin // Initialization

StringFormatedStream: = TStringStream.Create (""); // Copy from a simple stream to a string StringFormatedStream.CopyFrom (AData, AData.Size);

// Display the received message

Memol.Lines.Add (ABinding.PeerIP + "" + StringFormatedStream.DataString);

ABinding.SendTo (ABinding.PeerIP, ABinding.PeerPort, s, Length (s)); // Free the string stream StringFormatedStream.Free; end;

The event handler procedure has three parameters. The first is present in all handlers and does not carry anything interesting for us. The second is data that is received from the network. The third - it stores information about where the data came from.

So, the received data is stored in the second parameter. They come to us as a simple unformatted TStream. To make it more convenient to work with data, it is better to overtake them into a string stream. Do you think this is inconvenient? What if you are transferring not text, but a picture, and the component will format it into text? This will no longer be inconvenient, but a complete bummer!

See how easily everything turns into text. The handler declares one StringFormatedStream variable of type TStringStream (string stream). It is initialized by the first line of code. In the second line, data from the plain unformatted stream is copied to the string stream. Everything!!! The passed text is now in the Datastring property of the StringFormatedStream. After THIS MAJEY boldly DISPLAY this result in the Memo component.


Figure 4.24. Chat in action

But we are writing a chat, and it is desirable to also display information about who transmitted this text. For example, the IP address of the data sender is displayed, which is located in the property of the third parameter ABinding. But this is only for example, and in a real program it will look ugly. What is this mister 192.168.100.x talking about? Or maybe even the lady is talking about it. Therefore, you can add the sender's name directly to the sending text. The code will change as follows:

IdUDPClisntl. Send ("Put the sender's name here" Editl.Text); You can enable the user to enter a name on a separate Edit2 input line. In this case, the code will be like this; IdUDPClisntl.Send (Edit2.Text + "" + Editl.Text);

On the CD in the \ Examples \ Chapter 4 \ Chat directory, you can see an example of this program.

new player July 4, 2012 at 06:26 PM

Writing your ved bike in Delphi

  • Lumber room *

Good afternoon, Habrayuser. Honestly, I love the Delphi language, and I think that it has been unnecessarily forgotten. And in this topic, I would like to share with you the experience of writing a chat. This case is not very difficult, but very, very funny.

Introduction.

To write this very chat, I used the Borland Delphi 7 Lite IDE assembly. All libraries that were needed were already included.

Part I. Writing the interface.

Actually, this part is the easiest. First, we need to think about how our chat will work. I settled on manual selection of the port, server address, and nickname. In principle, you can choose the port yourself and specify it in the source code, but this way we can run as many copies of the program as we like in server mode until the ports run out. So, let's create four input fields, one Memo element, and three buttons. Don't forget to add two sockets, server and client. We write the text on the buttons. Program name, icon. Etc. This concludes the first part.

Part 2. The insides.

Here, in principle, there is not much work, but it is all important. First, we write the code for the buttons. It is below.

procedure TForm1. Button1Click (Sender: TObject);
begin
button2. Enabled: = false; // Disable the server button
Clsocket. address: = edit1. Text;
Clsocket. Port: = StrtoInt (edit2. Text); // Write down the port and IP
Clsocket. Active: = true; // enable socket
Clsocket. Open; // Open it
button3. enabled: = true; // Unblock the submit button
end;

And about the same with all the other buttons.

Nothing is needed for input fields.

Separately, I want to consider writing the code for the send message button, since it is very important.

procedure TForm1. Button3Click (Sender: TObject);
var f: integer; today: TdateTime;
begin
today: = now; // Find out the time
s1: = edit4. Text; // Form a string with a nickname and sending time
s2: = edit3. Text;
s3: = "[" + s2 + "] (" + TimetoStr (today) + "):" + s1; // Glue everything together
if clsocket. active = true then
ClSocket. Socket. SendText (s3) // Send a string to the server
else
begin
for f: = 0 to SrSocket. Socket. ActiveConnections - 1 do // Send on behalf of the server to all clients
begin
Srsocket. Socket. Connections [f]. SendText (s3);
end;
Memo1. lines. add (s3); // Write down a chat date for ourselves
end;
edit4. text: = "";
end;

And finally, we write the code for connecting / disconnecting / receiving a message. It is important not to forget to link events to procedures.

procedure TForm1. SrsocketClientRead (Sender: TObject;

var i: integer;
begin
Recieved: = Socket. ReceiveText (); // Transfer the received text to a variable
for i: = 0 to SrSocket. Socket. ActiveConnections - 1 do // Send the received info to all connected clients
Srsocket. Socket. Connections [i]. SendText (Recieved);
memo1. Lines. add (Recieved); // Write to ourselves
end;

procedure TForm1. SrSocketClientDisconnect (Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1. Lines. Add ( "Client disconnected") ; // Just notify the server
end;

procedure TForm1. SrSocketClientConnect (Sender: TObject; Socket: TCustomWinSocket);
begin
Memo1. Lines. Add ( "Client connected") ;
end;

Part 3. Final tests.

This part is the shortest. Add a name, version, build in the project settings, and draw an icon.

Also, after some searches on the Internet, I found this code for specifying the IP address, and included it in my chat.

function GetLocalIP: String;
const WSVer = $ 101;
var
wsaData: TWSAData;
P: PHostEnt;
Buf: array [0 .. 127] of Char;
begin
Result: = "";
if WSAStartup (WSVer, wsaData) = 0 then begin // I don't want to comment on anything here, because I'm not completely sure how it works
if GetHostName (@ Buf, 128) = 0 then begin
P: = GetHostByName (@ Buf);
if P<>nil then
Result: = iNet_ntoa (PInAddr (p ^. H_addr_list ^) ^);
end;
WSACleanup;
end;
end;

Actually, this is the whole chat. As you can see, it is very simple to write it. And I'm just grateful to you for your respect for this post.

Have a good day!

Tags: Delphi, programming

Good afternoon, Habrayuser. Honestly, I love the Delphi language, and I think that it has been unnecessarily forgotten. And in this topic, I would like to share with you the experience of writing a chat. This case is not very difficult, but very, very funny.

Introduction.

To write this very chat, I used the Borland Delphi 7 Lite IDE assembly. All libraries that were needed were already included.

Part I. Writing the interface.

Actually, this part is the easiest. First, we need to think about how our chat will work. I settled on manual selection of the port, server address, and nickname. In principle, you can choose the port yourself and specify it in the source code, but this way we can run as many copies of the program as we like in server mode until the ports run out. So, let's create four input fields, one Memo element, and three buttons. Don't forget to add two sockets, server and client. We write the text on the buttons. Program name, icon. Etc. This concludes the first part.

Part 2. The insides.

Here, in principle, there is not much work, but it is all important. First, we write the code for the buttons. It is below.

procedure TForm1. Button1Click (Sender: TObject);
begin
button2. Enabled: = false; // Disable the server button
Clsocket. address: = edit1. Text;
Clsocket. Port: = StrtoInt (edit2. Text); // Write down the port and IP
Clsocket. Active: = true; // enable socket
Clsocket. Open; // Open it
button3. enabled: = true; // Unblock the submit button
end;

And about the same with all the other buttons.

Nothing is needed for input fields.

Separately, I want to consider writing the code for the send message button, since it is very important.

procedure TForm1. Button3Click (Sender: TObject);
var f: integer; today: TdateTime;
begin
today: = now; // Find out the time
s1: = edit4. Text; // Form a string with a nickname and sending time
s2: = edit3. Text;
s3: = "[" + s2 + "] (" + TimetoStr (today) + "):" + s1; // Glue everything together
if clsocket. active = true then
ClSocket. Socket. SendText (s3) // Send a string to the server
else
begin
for f: = 0 to SrSocket. Socket. ActiveConnections - 1 do // Send on behalf of the server to all clients
begin
Srsocket. Socket. Connections [f]. SendText (s3);
end;
Memo1. lines. add (s3); // Write down a chat date for ourselves
end;
edit4. text: = "";
end;

And finally, we write the code for connecting / disconnecting / receiving a message. It is important not to forget to link events to procedures.

procedure TForm1. SrsocketClientRead (Sender: TObject;

var i: integer;
begin
Recieved: = Socket. ReceiveText (); // Transfer the received text to a variable
for i: = 0 to SrSocket. Socket. ActiveConnections - 1 do // Send the received info to all connected clients
Srsocket. Socket. Connections [i]. SendText (Recieved);
memo1. Lines. add (Recieved); // Write to ourselves
end;

procedure TForm1. SrSocketClientDisconnect (Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1. Lines. Add ( "Client disconnected") ; // Just notify the server
end;

procedure TForm1. SrSocketClientConnect (Sender: TObject; Socket: TCustomWinSocket);
begin
Memo1. Lines. Add ( "Client connected") ;
end;

Part 3. Final tests.

This part is the shortest. Add a name, version, build in the project settings, and draw an icon.

Also, after some searches on the Internet, I found this code for specifying the IP address, and included it in my chat.

function GetLocalIP: String;
const WSVer = $ 101;
var
wsaData: TWSAData;
P: PHostEnt;
Buf: array [0 .. 127] of Char;
begin
Result: = "";
if WSAStartup (WSVer, wsaData) = 0 then begin // I don't want to comment on anything here, because I'm not completely sure how it works
if GetHostName (@ Buf, 128) = 0 then begin
P: = GetHostByName (@ Buf);
if P<>nil then
Result: = iNet_ntoa (PInAddr (p ^. H_addr_list ^) ^);
end;
WSACleanup;
end;
end;

Actually, this is the whole chat. As you can see, it is very simple to write it. And I'm just grateful to you for your respect for this post.

Have a good day!

Tags: Delphi, programming