/**
* 9、 使用TCP协议写一个可以上传文件的服务器和客户端。
* @author 李宁
*
*/
public class Test9
{
public static void main(String[] args)
{}
}
//客户端
class Client
{
public static void main(String[] args) throws Exception
{
//建立Socket服务
Socket fileLoaderSocket = new Socket("168.168.168.94", 10005);
//从客户端本地读取文件,并写入socket的输出流中
OutputStream out = fileLoaderSocket.getOutputStream();
//实例化对象fileReader
InputStream fileRead = new FileInputStream("G:\\Demo.mp3");
//建立数组
byte[] buf = new byte[1024];
int len = 0;
//判断是否读到文件末尾
while((len=fileRead.read(buf)) != -1)
{
out.write(buf, 0, len);
}
//告诉服务端,文件已传输完毕
fileLoaderSocket.shutdownOutput();
//获取从服务端反馈的信息
BufferedReader in = new BufferedReader(new InputStreamReader(fileLoaderSocket.getInputStream()));
String serverBack = in.readLine();
System.out.println(serverBack);
//资源关闭
fileLoaderSocket.close();
fileRead.close();
}
}
//服务端
class Server
{
public static void main(String[] args) throws Exception
{
//建立服务端Socket
ServerSocket ss = new ServerSocket(10005);
//接收客户端Socket
Socket fileLoaderSocket = ss.accept();
//打印连接信息
String ip = fileLoaderSocket.getInetAddress().getHostAddress();
System.out.println(ip + "...conncected");
//接收文件,并保存
InputStream in = fileLoaderSocket.getInputStream();
//实例化对象fileSave
OutputStream fileSave = new FileOutputStream("E:\\server.mp3");
//建立数组buf
byte[] buf = new byte[1024];
int len = 0;
//判断是否读到文件末尾
while((len=in.read(buf)) != -1)
{
fileSave.write(buf, 0, len);
//刷新
fileSave.flush();
}
//返回文件复制情况信息
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fileLoaderSocket.getOutputStream()));
out.write("文件上传成功");
//刷新
out.flush();
//资源关闭
ss.close();
fileLoaderSocket.close();
fileSave.close();
}
}