//接收端
import
java.net.*;
import
java.io.*;
public
class
GetFile {
/**
* @param args
*/
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server =
null
;
Socket you =
null
;
String s =
null
;
DataOutputStream out =
null
;
DataInputStream in =
null
;
String path =
"D:/屏幕.jpg"
;
RandomAccessFile inFile;
byte
[] byteBuffer =
new
byte
[
1024
];
InputStream inSocket;
try
{
server =
new
ServerSocket(
4331
);
}
catch
(IOException e1){
System.out.println(
"ERRO:"
+e1);
}
try
{
you=server.accept();
// in = new DataInputStream(you.getInputStream());
// out = new DataOutputStream(you.getOutputStream());
// while(true){
// s=in.readUTF();
// out.writeUTF("你好:我是服务器");
// out.writeUTF("你说的数是:" + s);
//
// System.out.println("服务器收到:" + s);
// Thread.sleep(500);
//
// }
inSocket = you.getInputStream();
inFile =
new
RandomAccessFile(
new
File(path),
"rw"
);
int
amount;
while
((amount = inSocket.read(byteBuffer)) != -
1
) {
inFile.write(byteBuffer,
0
, amount);
}
inFile.close();
you.close();
server.close();
}
catch
(IOException e){
System.out.println(
""
+e);
}
}
}
//传送端
import
java.net.*;
import
java.io.*;
public
class
SendFile {
/**
* @param args
*/
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
String s =
null
;
Socket mysocket;
DataInputStream in =
null
;
DataOutputStream out =
null
;
RandomAccessFile outFile ;
byte
[] byteBuffer =
new
byte
[
1024
];
int
amount;
OutputStream outSocket;
String path = (
"D:/测试/屏幕.jpg"
);
try
{
mysocket =
new
Socket(
"111.117.111.196"
,
4331
);
outSocket = mysocket.getOutputStream();
//in = new DataInputStream(mysocket.getInputStream());
//out = new DataOutputStream(mysocket.getOutputStream());
//out.writeUTF("你好");
// while(true){
// s=in.readUTF();
// out.writeUTF(":" + Math.random());
// System.out.println("客户收到:" + s);
// Thread.sleep(500);
// }
outFile =
new
RandomAccessFile(
new
File(path),
"r"
);
while
((amount = outFile.read(byteBuffer)) != -
1
) {
outSocket.write(byteBuffer,
0
, amount);
System.out.println(
"文件发送中..."
);
}
outFile.close();
mysocket.close();
}
catch
(IOException e){
System.out.println(
"无法连接"
);
}
}
}
网上程序当来当去,本身BUG真是不少,还是自己动手亲自写比较好,改动的地方清晰可见。