package client;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 测试不用线程的效果,直接把接收到的数据保存到txt文件中
* @author lief
*
*/
public class NoThread {
private Socket soc=null;
private InputStream ins=null;
private String toip=null;
private int port=0;
private File file=null;
private FileOutputStream fos = null;
private BufferedOutputStream bos = null;
//private FileWriter fileWrite;
private String path = "voice.txt";
// private String logpath = "log.txt";
// private InputStream in = null;
public NoThread(String toip,int port){
this.toip=toip;
this.port=port;
}
/**
* 接收数据,保存在文件中
*/
public void Start(){
try {
soc=new Socket (toip,port);
System.out.println("连接成功");
ins=soc.getInputStream();
file=new File(path);
if(file.exists()){
file.delete();
file.createNewFile();
}
System.out.println("文件创建成功");
fos=new FileOutputStream(path,true);
bos=new BufferedOutputStream(fos);
int count = 0;
//重复读取数据流写入文件
while(true){
byte[] buffer=new byte[3752];
ins.read(buffer); //读取数据流
bos.write(buffer);
bos.flush(); //将缓冲区数据写入文件
count++;
System.out.println(count);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[]args){
new NoThread("192.168.137.10",8080).Start();
}
}