Java socket Communication-Transfer File images-transfer images
ClientTcpSend. java client sending class
Package com. yjf. test;
Import java. io. DataOutputStream;
Import java. io. File;
Import java. io. FileInputStream;
Import java.net. InetSocketAddress;
Import java.net. Socket;
Public class ClientTcpSend {
Public static String clientip = 127.0.0.1;
Public static int port = 33456;
Public static void main (String [] args ){
Int length = 0;
Byte [] sendBytes = null;
Socket socket = null;
DataOutputStream dos = null;
FileInputStream FCM = null;
Try {
Try {
Socket = new Socket ();
Socket. connect (new InetSocketAddress (clientip, port), 30*1000 );
Dos = new DataOutputStream (socket. getOutputStream ());
File file = new File (F: \ aa. xml );
FS = new FileInputStream (file );
SendBytes = new byte [1024*4];
While (length = FS. read (sendBytes, 0, sendBytes. length)> 0 ){
Dos. write (sendBytes, 0, length );
Dos. flush ();
}
} Finally {
If (dos! = Null)
Dos. close ();
If (FS! = Null)
FCM. close ();
If (socket! = Null)
Socket. close ();
}
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
ServerTcpListener. java Server listener class
Package com. yjf. test;
Import java.net .*;
Import java. io .*;
Public class ServerTcpListener implements Runnable {
Public static void main (String [] args ){
Try {
Final ServerSocket server = new ServerSocket (ClientTcpSend. port );
Thread th = new Thread (new Runnable (){
Public void run (){
While (true ){
Try {
System. out. println (start listening ...);
Socket socket = server. accept ();
System. out. println (with Link );
ReceiveFile (socket );
} Catch (Exception e ){
}
}
}
});
Th. run (); // start the thread to run
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public void run (){
}
Public static void receiveFile (Socket socket ){
Byte [] inputByte = null;
Int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
Try {
Try {
Dis = new DataInputStream (socket. getInputStream ());
Fos = new FileOutputStream (new File (E: \ aa. xml ));
InputByte = new byte [1, 1024*4];
System. out. println (start to receive data ...);
While (length = dis. read (inputByte, 0, inputByte. length)> 0 ){
Fos. write (inputByte, 0, length );
Fos. flush ();
}
System. out. println (complete receiving );
} Finally {
If (fos! = Null)
Fos. close ();
If (dis! = Null)
Dis. close ();
If (socket! = Null)
Socket. close ();
}
} Catch (Exception e ){
}
}
}
Java socket Communication-Transfer file pictures-transfer pictures