Due to the emergence of. net, a lot of development work has indeed become more advanced languages like English. Due to the object-oriented development and design, a lot of originally complicated operations are only involved in component development. For the front-end application layer, you only need to call attributes and Methods one by one. For example, to add a Document, first declare a Document object named doc, and then assign a value to the Document attribute:
Doc. Name = "test ";
Doc. FileFullName = "C: \ test.txt ";
Then, call the Add method of Document: int rl = doc. Add (). In this way, the document is uploaded by the component. To a specific path uploaded to the server or uploaded to the database server in binary format, only the components are available and the front-end developers do not need to understand it.
This method is also a good fit for framework code. Previously very difficult network communication operations have now been encapsulated by Microsoft in System. Net and System. Sockets, making our calls very simple. Therefore, to write an instant messaging program, we can do it as long as we understand the working mechanism of Socket.
Next, let's talk about my design ideas:
First, the server needs to create a TcpListener, which is responsible for receiving the Socket of the communication request sent by the client.
The client creates a TcpClient and converts the messages to be sent to a stream. Then, it can send the TcpListener to the server through Socket. Create another TcpListener to receive the reply message sent by the server or other clients forwarded to the current client.
In this way, the server and the client can communicate with each other.
However, this is far from enough, because we need to explain the transmitted stream. Through the definition of different streams, the server must determine how to operate it. Such as logging on, logging out, sending messages, and transferring files. Alternatively, I want to include the target address sent to other clients in the message. The best way is to create a common object library that both the server and the client understand. We may name it MessageBase. Here we define the MessageHeader and MessageBody objects. In this way, our target address can be written in MessageHeader. Then, we serialize MessageHeader and MessageBody to binary and transmit the data through Socket.
Based on the common MessageBase, the server deserializes the binary stream to create an object. In this way, the server will know the client address to be sent by the client.
At the same time, the MessageHeader can also contain the source address. Then, the server can create an address pool based on this information. When the message is sent again, the target address can be obtained directly from here.
Next, create two console programs and reference the client components and server components as the client program and server program respectively.
Then you can send and receive messages.