客户端代码:
public class TCP_upload {
static String path = "C://Users/小苏/Downloads/1046025.lrc";
public static void main(String[] args) {
Socket s = null;
FileInputStream fis = null;
try {
//1.创建Socket并绑定服务端监听端口
s = new Socket("localhost", 10001);
fis = new FileInputStream(path);
OutputStream os = s.getOutputStream();
byte[] buff = new byte[1024];
int len;
while((len = fis.read(buff)) != -1){
os.write(buff, 0, len);
}
//结束标记
s.shutdownOutput();
//接收服务端返回的信息
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(reader.readLine());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(s != null){
try {
//4.关闭资源
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服务端代码:
class TCPServer_upload{
static String path1 = "C://Users/小苏/Downloads/(复件)1046025.lrc";
public static void main(String[] args){
FileOutputStream fos = null;
try {
//1.创建服务端并绑定监听端口
ServerSocket ss = new ServerSocket(10001);
//2.接收客户端数据,是阻塞方法
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
//3.得到输入流,用客户端的输入流读客户端发送过来的数据
InputStream is = s.getInputStream();
byte[] buff = new byte[1024];
int len ;
fos = new FileOutputStream(path1);
while((len = is.read(buff)) != -1){
fos.write(buff, 0, len);
}
//通知客户端
OutputStream os = s.getOutputStream();
byte[] b = "复制完成".getBytes();
os.write(b );
s.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}