当前位置: 技术问答>java相关
如何利用socket传文件(不同格式的)?高分求救!!---在线等待
来源: 互联网 发布时间:2017-03-12
本文导语: 如何利用socket传文件(不同格式的)?高分求救!!---在线等待 | 发送端: Socket sout = ...... File file = new File(filename); FileInputStream fin = new FileInputStream(file); byte buf[]=new byte[50000]; int len...
如何利用socket传文件(不同格式的)?高分求救!!---在线等待
|
发送端:
Socket sout = ......
File file = new File(filename);
FileInputStream fin = new FileInputStream(file);
byte buf[]=new byte[50000];
int len = fin.read(buf);
while(len > -1){
sout.write(buf, 0, len);
len = fin.read(buf);
}
fin.close();
接收端:
PostDataLen为总的传递字节数
in为一Socket
byte[] ch = new byte[2048];
int readLen = 0;
int len = 0;
while(PostDataLen > 0){
readLen = (PostDataLen > 2048)?2048:PostDataLen;
len = in.read(ch, 0, readLen);
postbuf.append(ch, 0, len);
PostDataLen -= len;
}
Socket sout = ......
File file = new File(filename);
FileInputStream fin = new FileInputStream(file);
byte buf[]=new byte[50000];
int len = fin.read(buf);
while(len > -1){
sout.write(buf, 0, len);
len = fin.read(buf);
}
fin.close();
接收端:
PostDataLen为总的传递字节数
in为一Socket
byte[] ch = new byte[2048];
int readLen = 0;
int len = 0;
while(PostDataLen > 0){
readLen = (PostDataLen > 2048)?2048:PostDataLen;
len = in.read(ch, 0, readLen);
postbuf.append(ch, 0, len);
PostDataLen -= len;
}
|
1、建立SOCKET连接
2、先传送文件的名称
3、以二进制流的方式传送文件内容
2、先传送文件的名称
3、以二进制流的方式传送文件内容
|
都是用流传递的,什么格式都没问题
|
在网络中传递的都是流,没有格式这种说法,比如你想传递某种格式的数据,你应该先将它转化成字节的形式,也就是流之后在接受端将接受到的数据按某种格式进行编码。
|
楼上差不多,只是中间要多一个传递文件名和创建文件的操作
|
发送方:
BufferedReader in =
new BufferedReader(
new FileReader(filename));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream()));
int i = 0;
while ((in = in.read())!= -1)
{ out.write(i);
}
out.flush();
out.close();
in.close();
接受方与发送方类似
BufferedReader in =
new BufferedReader(
new FileReader(filename));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream()));
int i = 0;
while ((in = in.read())!= -1)
{ out.write(i);
}
out.flush();
out.close();
in.close();
接受方与发送方类似
|
利用数据报包在网上传输流对象
ObjectInputStream is;
ServerSocket servSock = new ServerSocket(6000);
Sock sock;
sock = servSock.accept();
is = new ObjectInputStream( new
BufferedInputStream(sock.getInputStream()));
Factory o = (Factory)is.readObject();
ObjectInputStream is;
ServerSocket servSock = new ServerSocket(6000);
Sock sock;
sock = servSock.accept();
is = new ObjectInputStream( new
BufferedInputStream(sock.getInputStream()));
Factory o = (Factory)is.readObject();