Client (PHP):
send.php
[php]
$fp = fsockopen("127.0.0.1", 1024, $errno, $errstr, 10);
$filename = '2012_07_23.zip'; //File to be sent
fwrite($fp, $filename . "rn"); //Write the file name. Use .readLine() on the java side. The first line is the file name
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
//fwrite($fp,$contents); //Small files can be sent like this, but large files should be divided into segments
$data_size = 1024 * 1; //1M each time
$data_count = ceil( strlen($contents) / $data_size ); //How many pieces of data are there
for( $i = 0; $i < $data_count; $i ++ )
{
$data = substr( $contents, $i * $data_size, $data_size ); //Write to transmission socket
fwrite($fp,$data); www.2cto.com
}
fclose($fp);
?>
Server (JAVA):
MyApp.java
[java]
import java.io.*;
import java.net.*;
import java.util.Date;
import java.sql.*;
public class MyApp
{
private int x;
Public MyApp()
{
x = 0;
}
Public static void main(String args[]) {
int i = 1, port = 1024;
ServerSocket server=null;
Socket client = null;
try{
server=new ServerSocket(port);
System.out.println("Web Server is listening on port" + server.getLocalPort());
for(;;){
client=server.accept();
//Accept the client’s connection request
new WebThread(client,i).start();
i++;
}catch(Exception e){System.out.println(e);}
}
}
WebThread.java
[java]
import java.io.*;
import java.net.*;
import java.util.Date;
class WebThread extends Thread{
Socket socket;//Socket word to connect to the web browser
int counter;//Counter
Public WebThread(Socket cl,int c){
socket=cl;
counter=c;
}
Public void run()//Thread body
{
Try
DataInputStream inputStream = null;
Try
inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}catch(Exception e)
try
String savePath = "E:\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
String filename = new String();
filename = inputStream.readLine();
String saveFilePath = new String();
saveFilePath = savePath + "\" + filename;
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(saveFilePath))));
System.out.println("The long name of the file: " + filename);
int read = 0;
If (inputStream != null)
read = inputStream.read(buf);
If (read == -1) {
break;
//System.out.println(buf.toString());
fileOut.write(buf, 0, read);
System.out.println("Reception completed, file saved as" + saveFilePath + "n");
fileOut.flush();
fileOut.close();
inputStream.close();
} catch (Exception e) {
System.out.println("Error in receiving message" + e.toString() + "n");
Return;
}catch(Exception e){
}
}
}
Author: junqing124
http://www.bkjia.com/PHPjc/478073.html