Client端
/*
* 文件上传案例的客户端:读取本地文件,上传到服务器,读取服务器回写的数据
**/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("d:\\a.txt");
Socket socket = new Socket("127.0.0.1",8888);
OutputStream os = socket.getOutputStream();
// int l = 0;
// while ((l = fis.read()) != -1){
// System.out.print((char)l);
// }
System.out.println("开始传输文件...");
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1){
// System.out.println(new String(bytes,0,len));
os.write(bytes,0,len); //从本地读取,写道服务器去了
}
socket.shutdownOutput(); //此处不写,Server端Socket流不会结束,后面的代码不会执行
//获取服务器反馈数据
InputStream is = socket.getInputStream();
while ((len = is.read(bytes)) != -1){
System.out.println(new String(bytes,0,len) );
}
fis.close();
socket.close();
}
}
Server端:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
Socket accept = server.accept();
InputStream is = accept.getInputStream();
FileOutputStream fos = new FileOutputStream("d:\\CC\\a.txt");
int len = 0;
byte[] bytes = new byte[1024];
//注意:此处要接收Client主动发送过来的-1(结束,socket.shutdownOutput)标记才行
//否则is.read()流一直等待,循环不会结束
while ((len = is.read(bytes)) != -1){
fos.write(bytes,0,len); //读取网络流文件并写入到本地服务器指定地址
}
//给Client端发反馈消息
OutputStream os = accept.getOutputStream();
os.write("文件传输完毕.".getBytes());
//关闭流
fos.close();
accept.close();
server.close();
}
}