Android socket realizes simple chat function and file transfer

Doing the program is a boring and repetitive thing. Whenever I feel impetuous, I will look for a novel to read. I have loved reading martial arts novels since I was a child and have always had a martial arts dream. From Jin Yong, Gu Long, Liang Yusheng series to Fengge (Kunlun), sun Xiao (Heroic Chronicle) and Xiao Ding's (killing immortals) let me appreciate different Jianghu.

If you have a good series of martial arts novels, leave me a message. That's all the digression. Then it's technology.

Take a look at the functional renderings implemented today:

Multiple mobile phones can be used here for communication, and I use the server to send messages.

Is it just sending messages? Some seem too monotonous. OK, add file transfer on the basis of sending messages. In the later stage, the transmission of video and audio will be increased, and the expression package will be added. Let's take a look at the renderings of graphic messages and lead you to realize the simple chat function of communication.

Difficulties to be solved:

How to determine whether the data received by the socket is a string or a stream?

If you are an old driver, please leave a message and give your valuable opinions. With this question, let's go on.

Socket overview

Socket we call it "socket", which is used for message notification system (such as laser push), current communication system (such as ring letter), etc. Used to describe IP address and port. It is a handle to the communication chain. Two programs on the network realize data exchange through a two-way communication connection. One end of the two-way link is called a socket. A socket is uniquely determined by an IP address and a port number (such as ServerSocket). Applications usually send requests to or respond to network requests through "sockets". Socket is a very popular programming interface of TCP / IP protocol. However, the types of protocols supported by socket are not only TCP / IP, so there is no inevitable relationship between them. In the Java environment, socket programming mainly refers to network programming based on TCP / IP protocol.

There are two classes under the java.net package: socket and ServerSocket, which are based on TCP protocol.

This article mainly explains socket and ServerSocket.

Socket connection

Establishing a socket connection requires at least one pair of sockets, one of which runs on the client, called ClientSocket, and the other runs on the server, called ServerSocket.

The connection process between sockets is divided into three steps: server listening, client request and connection confirmation. The steps are as follows:

JDK Socket

There are two classes under the java.net package: socket and ServerSocket. ServerSocket is used on the server side. Socket is used when establishing network connection. When the connection is successful, a socket instance will be generated at both ends of the application. Operate this instance to complete the required session. For a network connection, sockets are equal, there is no difference, and there are no different levels on the server side or on the client side. No matter socket or ServerSocket, their work is completed through socketimpl class and its subclasses. Next, learn about the construction methods of socket and ServerSocket.

Socket

Socket construction method:

Parameter meaning:

Note: we need to pay special attention when selecting the port number. Each port provides a specific service. Only by giving the correct port can we obtain the corresponding service. The port numbers from 0 to 1023 are reserved by the system. For example, the port number of HTTP service is 80, the port number of Telnet service is 21, and the port number of FTP service is 23. The port number selected in this paper is 30003

Several important socket methods:

Convection operation, remember to handle and close after operation. And the handling of convection anomalies.

ServerSocket

Construction method of ServerSocket:

Then let's take a look at the case.

Send and receive messages

First, let's implement a simple case. The server always listens to a port and waits for the client to connect. The client connects to the server according to the IP address and port number, and then the customer service sends a message to the server through the console. The server receives the message and displays it. Let's take a look at the specific implementation steps:

ClientSocket customer service end:

The two socket parameters are IP address and port number respectively. You can obtain the IP address through the following code:

Note: turn off redundant network adaptation and only keep the current network connection. Turn off the firewall and the security software. Otherwise, the connection may not be connected.

ServerSocket server:

The port numbers of the server and customer service must be consistent. Let's run two Java programs to see the effect:

Some children's shoes may not know how to run Java programs under Android studio. Please see the screenshot below:

transfer files

The socket can only read messages through the stream. To transfer files, you need to solve the problem raised at the beginning of the article. How to judge whether the data received by the socket is a string or a stream?

Define protocol

In order to ensure that the received data types are uniform (whether the data is a string or a stream), it is necessary to define a protocol. There are many ways to define protocols:

The principle of the custom protocol I use here is similar to the previous two. I transmit JSON data. The transmitted string or stream is identified according to the field, and the receiver can parse the data according to the identification.

Entity class of the protocol (transmission):

Identify the type of transmission (serialization) or reception (deserialization) according to the field transmissiontype. The transmission process always exists in JSON format. When transferring files, you need to convert the stream into a string (there are many ways. I use base64 encryption and decryption).

Client (clientthread)

The code of the file sent by the client is as follows:

I will attach the source code at the end of the article.

Convert the byte stream into a string and transfer it to base64utils. Encode (bytes). The receiver parses the string into a byte stream and writes it to the file.

Note: when running in the Android program, remember to add the permission to read and write network files.

Server thread

The code of the file received by the server is as follows:

The server receives the file and stores it in disk D. Note that the stream is closed after the file transfer is completed.

Source address: socketdemo_ jb51.rar

After downloading the source code, first replace the host address in the constants class, then run the Java program of Myserver, and finally run the Android program of mainactivity.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>