客户端
public class client {
public static void main(String[] args) {
try(Socket socket =new Socket("localhost",8080)) {
FileInputStream fileInputStream =new FileInputStream("test.txt");
OutputStream stream =socket.getOutputStream();
byte[] bytes =new byte[1024];
int i;
while((i=fileInputStream.read(bytes))!=-1){
stream.write(bytes,0,i);
}
fileInputStream.close();
stream.flush();
}catch (IOException e){
System.out.println("服务端连接失败");
e.printStackTrace();
}
}
}
服务端
public class server {
public static void main(String[] args) {
try(ServerSocket server =new ServerSocket(8080)) {
Socket socket = server.accept();//没有客户端连接会阻塞
InputStream stream = socket.getInputStream();
FileOutputStream fileOutputStream =new FileOutputStream("net/data.txt");
byte[] bytes =new byte[1024];
int i;
while((i=stream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,i);
}
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("客户端已连接。IP地址为"+socket.getInetAddress().getHostAddress());
}catch (IOException e){
e.printStackTrace();
}
}
}