Java binary file transfer based on TCP

A complete example of file transmission based on java socket protocol is completed based on TCP communication.

In addition to the binary file transmission based on TCP, it also demonstrates some programming skills of Java swing, demo program

The main functions are as follows:

First, let's take a look at the relationship between the classes of the whole Dome:

The functions and code implementation of each class are explained in detail below according to the above figure:

Server side:

The first function of the filetransferserver class is to create a server socket on port 9999 and

Start listening for connections. Relevant codes are as follows:

With regard to propertychangelister, Java provides a very powerful tool class to monitor the data changes of any bean model. The program realizes the monitoring by adding this listener

Capture the event when the value of the progress property of swingworker changes, and then update the jpprogressbar

Instance object to refresh the UI. The complete source code of filetransferserver class is as follows:

Filereceivetask is a server-side file acceptance class: first get the file name and file size from the established TCP stream, and then start accepting file content bytes

And write to the created file object stream. Finally, verify whether the file size is equal to the written byte stream

Finally, send a message to the file sender to tell the other party that the file transmission is completed and the TCP stream can be closed.

The complete source code of this class is as follows:

Client: filetransferclient is a client UI class used to connect to the server, and then select

Files to be transferred (pictures, PDF, word documents and other binary files). without

Enter the server information, and a prompt will pop up for input. The port has been specified as: 9999

The [send file] button will open the file selection box. After the user selects the file to be transferred, create it

Filetransfertask thread and starts executing file transfer. The client UI code is as follows:

Filetransfertask implements the following functions:

The complete source code of this class is as follows:

The packet classes are as follows, which are not explained!

The maximum number of bytes sent each time is 2048 bytes. The final running effect of the program is as follows (win7 + jdk6u30):

The above is the whole content of this article. I hope it will be helpful to your study.

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
分享
二维码
< <上一篇
下一篇>>