Server
public class PictureTestServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(0)) {
System.out.println("服务器已启动,监听端口: " + serverSocket.getLocalPort());
Socket socket = serverSocket.accept();
// 读取图片文件
File file = new File("F:/picture/client/water.webp");
try (FileInputStream fileInputStream = new FileInputStream(file);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
服务器托管网 byte[] buffer = new byte[(int) file.length()];
fileInputStream.read(buffer);
// 发送图片文件到客户端
dataOutputStream.write(buffer, 0, buffer.length);
System.out.println("图片发送成功");
}
// 关闭套接字
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client
public class PictureTestClient {
public static void main(String[] args) {
try {
// 该端口为Server启动后监听的端口
Socket socket = new Socket("localhost", 50966);
// 从服务器接收图片文件
InputStream inputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("F:/picture/server/water.webp");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
服务器托管网 }
System.out.println("图片接收成功");
// 关闭流和套接字
fileOutputStream.close();
inputStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
先启动Server监听端口,获取到的端口替换掉Client端口,再启动Client端口
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
C++是如何工作的 #include int main() { std::cout “Hello World” std::endl; std::cin.get(); } 首先是预处理,会将iostream文件的内容拷贝到当前文件,这就是头文件,main函数是程…