客戶端(PHP):
send.php
[php]
<?php
$fp = fsockopen("127.0.0.1", 1024, $errno, $errstr, 10);
$filename = '2012_07_23.zip'; //要發送的文件
fwrite($fp, $filename . "\r\n"); //寫入文件名 java端用.readLine()..第一行就是文件名
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
//fwrite($fp,$contents); //小文件可以這樣發,但大文件請分段
$data_size = 1024 * 1; //每次1M
$data_count = ceil( strlen($contents) / $data_size ); //有多少塊數據
for( $i = 0; $i < $data_count; $i ++ )
{
$data = substr( $contents, $i * $data_size, $data_size ); //寫入到傳輸socket
fwrite($fp,$data); www.2cto.com
}
fclose($fp);
?>
服務端(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();
//接受客戶機的連接請求
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;//連接Web浏覽器的socket字
int counter;//計數器
public WebThread(Socket cl,int c){
socket=cl;
counter=c;
}
public void run()//線程體
{
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("文件長名為:" + filename);
while (true)
{
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("接收完成,文件存為" + saveFilePath + "\n");
fileOut.flush();
fileOut.close();
inputStream.close();
} catch (Exception e) {
System.out.println("接收消息錯誤" + e.toString() + "\n");
return;
}
}catch(Exception e){
}
}
}
作者:junqing124