简单的Tcp链接文件传输程序

import java.net.*;
import java.io.*;


//客户端
class SendClient{

public static void main(String[] args) throws Exception{
//建立客户端
Socket client = new Socket("127.0.0.1", 10008);

//获取文件流
BufferedReader bufr = new BufferedReader(new FileReader(new File("新建文本文档.txt")));

//获取客户端输出流,向服务端发送数据
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);

// BufferedWriter bufwout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

//获取客户端输入流,接收服务端的服务信息
BufferedReader bufrin = new BufferedReader(new InputStreamReader(client.getInputStream()));

//发送文件
String text = null;

while((text = bufr.readLine())  != null){

//发送数据
pw.println(text);


// bufwout.write(text, 0, text.length());
// bufwout.newLine();
// bufwout.flush();

}
client.shutdownOutput();


String request = null;
//接收数据
request = bufrin.readLine();
System.out.println(request);


bufr.close();
client.close();

}
}


//服务端
class ReceServer{

public static void main(String[] args) throws Exception{

//建立服务端点
ServerSocket server = new ServerSocket(10008);

//获取客户端
Socket client = server.accept();
System.out.print("connected");

//获取客户端输入网络流
BufferedReader bufrin = new BufferedReader(new InputStreamReader(client.getInputStream()));
//关联保存文件流
BufferedWriter bufw = new BufferedWriter(new FileWriter(new File("收到的文件.txt")));
//获取客户端输出网络流
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);

// BufferedWriter bufwout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

//循环处理用户请求
String text = null;
while((text = bufrin.readLine()) != null){

//pw.println(request.toUpperCase());
bufw.write(text, 0, text.length());
bufw.newLine();
bufw.flush();

// bufwout.write(request.toUpperCase(), 0, request.length());
// bufwout.newLine();
// bufwout.flush();

}
pw.println("上传成功!");


//关闭资源

bufw.close();
bufrin.close();
client.close();
}
}





你可能感兴趣的:(简单的Tcp链接文件传输程序)