Java Chat Server: 定时发送文件
import java.io.; import java.net.;
public class ChatServer { public static void main(String[] args) throws IOException { // 创建ServerSocket对象,监听端口17500 ServerSocket serverSocket = new ServerSocket(17500); System.out.println('服务器已启动,正在监听端口 ' + serverSocket.getLocalPort() + ' ...');
while (true) {
// 接收客户端连接,创建Socket对象
Socket socket = serverSocket.accept();
System.out.println('接收到来自 ' + socket.getInetAddress().getHostAddress() + ':' + socket.getPort() + ' 的连接。');
// 启动新线程处理客户端请求
new Thread(() -> {
try {
// 创建SocketUtil对象
SocketUtil socketUtil = new SocketUtil(socket);
// 发送文件并等待客户端断开连接
socketUtil.outByFile('data');
System.out.println('成功发送文件给 ' + socket.getInetAddress().getHostAddress() + ':' + socket.getPort() + ' 。');
} catch (IOException e) {
System.err.println('处理客户端请求时出现异常:' + e.getMessage());
}
}).start();
}
}
static class SocketUtil {
private InputStream is;
private OutputStream os;
public SocketUtil(Socket socket) throws IOException {
// 获取输入输出流
this.is = socket.getInputStream();
this.os = socket.getOutputStream();
}
public void outByFile(String filePath) throws IOException {
String path = ChatServer.class.getResource(filePath).getPath();
FileInputStream fis = null;
try {
// 读取文件内容,并写入输出流
fis = new FileInputStream(path);
byte[] buffer = new byte[8129];
int len;
long lastTime = System.currentTimeMillis();
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
os.flush();
if (System.currentTimeMillis() - lastTime >= 6 * 60 * 1000) {
System.out.println('响应客户端请求,发送文件 ' + filePath + '。');
lastTime = System.currentTimeMillis();
}
}
os.flush();
// 等待客户端断开连接
while (is.available() > 0) {
Thread.sleep(100);
}
} catch (FileNotFoundException e) {
System.err.println('文件 ' + filePath + ' 不存在。');
} catch (IOException e) {
System.err.println('发送文件 ' + filePath + ' 时出现异常:' + e.getMessage());
} catch (InterruptedException e) {
System.err.println('等待客户端断开连接时出现异常:' + e.getMessage());
}
}
}
}
原文地址: https://www.cveoy.top/t/topic/lHem 著作权归作者所有。请勿转载和采集!