求client接收server通过socket发送的实时传输的二进制流代码?
在client端实时接收二进制流,server实时在传输,能否提供在client通过byte[]接收定长(如2048)的流数据,并写入文件中。感谢!!!
------解决方案--------------------这是可以实现的哦。
在接收的时候就是按照流的方式来收发。
------解决方案--------------------http://www.roboticfan.com/blog/user_2005/104/archives/2007/2007128191242.shtml
楼主可以去看看
------解决方案--------------------server发, client接收, 发完了就flush,最好再加个标志位, client端收到标志位后停止接收,然后把缓冲区数据写文件即可.
------解决方案--------------------服务器:
////////////////////////////////////
package io.socket;
import java.io.BufferedOutputStream;
import java.io.File;
import
java.io.FileNotFoundException;
import
java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStreamImpl;
public class fileServer {
public fileServer() throws
FileNotFoundException,
IOException {
ImageInputStreamImpl fis = null;
File pic = new File( "D:/WEB/pic/tyjx.jpg ");
fis = new FileImageInputStream(pic);
System.out.println(fis.length());
byte[] buffer = new byte[(int) pic.length()];
System.out.println( "buffer: " + buffer.length);
try {
ServerSocket s = new ServerSocket(4700);
System.out.println( "Server started! ");
fis.read(buffer, 0, buffer.length);
while (true) {
Socket s1 = s.accept();
BufferedOutputStream bout = new BufferedOutputStream(s1
.getOutputStream());
bout.write(buffer, 0, buffer.length);
bout.flush();
System.out.println( "pic sented by the server!!! ");
System.out.println( "pic length: " + buffer.length);
bout.close();
}
} catch (IOException ex) {
}
}
public static void main(String[] args) {
try {
new fileServer();
} catch (File
NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//////////////////////////////
客户端
//////////////////////////////
package io.socket;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
public class fileClient {
public static void main(String[] args) {
new fileClient();
}
public fileClient() {
Socket s1 = null;
BufferedInputStream in = null;
FileOutputStream fos = null;
byte[] buffer = new byte[102400];
// byte[] buffer = null;
try {
s1 = new Socket( "127.0.0.1 ", 4700);
in = new BufferedInputStream(s1.getInputStream());
in.read(buffer);
File pic = new File( "D:/WEB/pic/tyjxTT.jpg ");
fos = new FileOutputStream(pic);
System.out.println( "buffer length: " + buffer.length);
fos.write(buffer);
} catch (IOException e) {
}
}
}
////////////////////
仅供参考,hoho