fileserver.java

来自「一个简单的socket聊天工具,实现在发送文件和语音聊天等功能,还能聊天的同时听」· Java 代码 · 共 63 行

JAVA
63
字号
/*
 * Created on 2006-2-25
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author 之诸暇
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.io.*; 
import javax.swing.JFrame;
import javax.swing.ProgressMonitorInputStream;
import java.net.*; 



public class FileServer{ 
	private JFrame myframe;
	private File file;
	private ProgressMonitorInputStream pm;
	
	public FileServer(JFrame frame,File getfile)throws Exception{ 

		//创建文件流用来读取文件中的数据  
		file = getfile; 
		myframe = frame;
		FileInputStream fos=new FileInputStream(file); 
		pm = new ProgressMonitorInputStream(myframe,"已完成",fos);

		//创建网络服务器接受客户请求 

		ServerSocket ss=new ServerSocket(3108); 
		Socket client=ss.accept(); 



		//创建网络输出流并提供数据包装器 
		OutputStream netOut=client.getOutputStream(); 
		OutputStream doc=new DataOutputStream(new BufferedOutputStream(netOut)); 



		//创建文件读取缓冲区 
		byte[] buf=new byte[2048]; 
		int num=fos.read(buf); 
		while(num!=(-1)){//是否读完文件 
			doc.write(buf,0,num);//把文件数据写出网络缓冲区 
			doc.flush();//刷新缓冲区把数据写往客户端 
			num=fos.read(buf);//继续从文件中读取数据 

		} 

		pm.close();
		fos.close(); 
		doc.close(); 

	} 
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?