Example of using Java Socket to transmit images

Source: Internet
Author: User

 

After finding a Java Socket Image Transmission example on the Internet for a long time, you can directly use

It will be useful in the future.

 

Server:

 

Java code:

Import java. Io. bufferedinputstream;
Import java. Io. datainputstream;
Import java. Io. dataoutputstream;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java.net. serversocket;
Import java.net. Socket;

Public class servertest {
Int Port = 8821;

Void start (){
Socket S = NULL;
Try {
Serversocket Ss = new serversocket (port );
While (true ){
// Select the file for Transmission
String filepath = "d :\\ update \ image \ 5.jpg ";
File Fi = new file (filepath );

System. Out. println ("file length:" + (INT) Fi. Length ());

// Public socket accept () throws
// Ioexception listens and is connected to this socket. This method is blocked until the connection is established.

S = ss. Accept ();
System. Out. println ("establish socket link ");
Datainputstream Dis = new datainputstream (New bufferedinputstream (S. getinputstream ()));
Dis. readbyte ();

Datainputstream FD = new datainputstream (New bufferedinputstream (New fileinputstream (filepath )));
Dataoutputstream PS = new dataoutputstream (S. getoutputstream ());
// Send the file name and length to the client. All platforms need to be applied here, such as processing the Chinese name. For details, see the ready-made code in think in Java 4th.
PS. writeutf (Fi. getname ());
PS. Flush ();
PS. writelong (long) Fi. Length ());
PS. Flush ();

Int buffer size = 8192;
Byte [] Buf = new byte [buffersize];

While (true ){
Int READ = 0;
If (FS! = NULL ){
Read = FCM. Read (BUF );
}

If (read =-1 ){
Break;
}
PS. Write (BUF, 0, read );
}
PS. Flush ();
// Disable the socket link. Otherwise, the client will wait for the server's data to come,
// Data is incomplete until the socket times out.
FCM. Close ();
S. Close ();
System. Out. println ("file transfer completed ");
}

} Catch (exception e ){
E. printstacktrace ();
}
}

Public static void main (string Arg []) {
New servertest (). Start ();
}
}

 

Specific implementation:

Java code:

Package serverphoto;

Import java.net .*;
Import java. Io .*;

Public class clientsocket {
Private string IP;

Private int port;

Private Socket socket = NULL;

Dataoutputstream out = NULL;

Datainputstream getmessagestream = NULL;

Public clientsocket (string IP, int port ){
This. IP = IP;
This. Port = port;
}

/***//**
* Create a socket connection
*
* @ Throws exception
* Exception
*/
Public void createconnection () throws exception {
Try {
Socket = new socket (IP, Port );
} Catch (exception e ){
E. printstacktrace ();
If (socket! = NULL)
Socket. Close ();
Throw E;
} Finally {
}
}

Public void sendmessage (string sendmessage) throws exception {
Try {
Out = new dataoutputstream (socket. getoutputstream ());
If (sendmessage. Equals ("Windows ")){
Out. writebyte (0x1 );
Out. Flush ();
Return;
}
If (sendmessage. Equals ("Unix ")){
Out. writebyte (0x2 );
Out. Flush ();
Return;
}
If (sendmessage. Equals ("Linux ")){
Out. writebyte (0x3 );
Out. Flush ();
} Else {
Out. writeutf (sendmessage );
Out. Flush ();
}
} Catch (exception e ){
E. printstacktrace ();
If (OUT! = NULL)
Out. Close ();
Throw E;
} Finally {
}
}

Public datainputstream getmessagestream () throws exception {
Try {
Getmessagestream = new datainputstream (New bufferedinputstream (socket. getinputstream ()));
Return getmessagestream;
} Catch (exception e ){
E. printstacktrace ();
If (getmessagestream! = NULL)
Getmessagestream. Close ();
Throw E;
} Finally {
}
}

Public void shutdownconnection (){
Try {
If (OUT! = NULL)
Out. Close ();
If (getmessagestream! = NULL)
Getmessagestream. Close ();
If (socket! = NULL)
Socket. Close ();
} Catch (exception e ){

}
}
}

 

Client:

Java code:

Package serverphoto;

 

Import java. Io. bufferedoutputstream;
Import java. Io. datainputstream;
Import java. Io. dataoutputstream;
Import java. Io. fileoutputstream;

Public class clienttest {
Private clientsocket cs = NULL;

Private string IP = "localhost"; // set it to the server IP Address

Private int Port = 8821;

Private string sendmessage = "windwos ";

Public clienttest (){
Try {
If (createconnection ()){
Sendmessage ();
Getmessage ();
}

} Catch (exception ex ){
Ex. printstacktrace ();
}
}

Private Boolean createconnection (){
Cs = new clientsocket (IP, Port );
Try {
CS. createconnection ();
System. Out. Print ("the server is connected successfully! "+" \ N ");
Return true;
} Catch (exception e ){
System. Out. Print ("failed to connect to the server! "+" \ N ");
Return false;
}

}

Private void sendmessage (){
If (cs = NULL)
Return;
Try {
CS. sendmessage (sendmessage );
} Catch (exception e ){
System. Out. Print ("failed to send message! "+" \ N ");
}
}

Private void getmessage (){
If (cs = NULL)
Return;
Datainputstream inputstream = NULL;
Try {
Inputstream = cs. getmessagestream ();
} Catch (exception e ){
System. Out. Print ("message receiving cache error \ n ");
Return;
}

Try {
// Local save path. The file name is automatically inherited from the server.
String savepath = "D: \ update \\";
Int buffer size = 8192;
Byte [] Buf = new byte [buffersize];
Int passedlen = 0;
Long Len = 0;

Savepath + = inputstream. readutf ();
Dataoutputstream fileout = new dataoutputstream (New bufferedoutputstream (New fileoutputstream (savepath ))));
Len = inputstream. readlong ();

System. Out. println ("file length:" + Len + "\ n ");
System. Out. println ("start to receive files! "+" \ N ");

While (true ){
Int READ = 0;
If (inputstream! = NULL ){
Read = inputstream. Read (BUF );
}
Passedlen + = read;
If (read =-1 ){
Break;
}
// The following progress bar is based on prograssbar in the graphic interface. If a file is played here, the same percentage may be printed again.
System. Out. println ("the file received" + (passedlen * 100/Len) + "% \ n ");
Fileout. Write (BUF, 0, read );
}
System. Out. println ("received successfully, the file is saved as" + savepath + "\ n ");

Fileout. Close ();
} Catch (exception e ){
System. Out. println ("Receive message error" + "\ n ");
Return;
}
}

Public static void main (string Arg []) {
New clienttest ();
}
}

 

Start the server and the image will be read automatically. When the client is started, the file is automatically downloaded to the specified address.

It is good for learning and program testing.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.