|
Сервер-сокет зависание
#38466091
Ссылка:
Ссылка на сообщение:
Ссылка с названием темы:
|
|
|
|
Есть серверное приложение (для передачи файлов) написанное на java проблема в следующем - раз в сутки оно отключается само код приведен ниже. Есть логи на момент отключения в них никаких особых казусов не выявлено.
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50.
package servercopyfilem;
import java.io.*;
import java.net.*;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class ServerCopyFileM {
static Logger log = Logger.getLogger(ServerClientConn.class);
static Logger logDeb = Logger.getLogger("logDeb");
final static int port=2011;
private static ServerSocket sSocket;
private static Socket socket;
public static void main(String[] args) throws IOException{
PropertyConfigurator.configure("src/log4j.properties");
try
{
sSocket=new ServerSocket(port);
logDeb.debug("Создан сервер сокет");
}catch(IOException e){
logDeb.debug("Не могу создать сервер сокет");
}
try
{
while (true){
socket=sSocket.accept();
try
{
logDeb.debug("Пытаюсь подключить клиента");
new Thread(new ServerClientConn(socket, log, logDeb)).start();
}catch(IOException e){
logDeb.debug("Не могу создать клиентский сокет");
socket.close();
}
}
}catch(IOException exc){}
finally{
try
{
logDeb.debug("Завершения программы");
sSocket.close();
}catch(IOException excp){logDeb.debug("Программа завершена с ошибкой");}
}
}
}
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137. 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170. 171. 172. 173. 174. 175. 176. 177. 178. 179. 180. 181. 182. 183. 184. 185. 186. 187. 188. 189. 190. 191. 192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202. 203. 204. 205. 206. 207. 208. 209. 210. 211. 212. 213. 214. 215. 216. 217. 218. 219. 220. 221. 222. 223. 224. 225. 226. 227. 228. 229. 230. 231. 232. 233. 234. 235. 236. 237. 238. 239. 240. 241. 242. 243. 244. 245. 246. 247. 248. 249. 250. 251. 252. 253. 254. 255. 256. 257. 258. 259. 260. 261. 262. 263. 264. 265. 266. 267. 268. 269. 270. 271. 272. 273. 274. 275. 276. 277. 278.
package servercopyfilem;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import org.apache.log4j.Logger;
//import org.apache.log4j.PropertyConfigurator;
public class ServerClientConn implements Runnable{
//Logger log = Logger.getLogger(ServerClientConn.class);
private ArrayList<Path> listFilesTransfer= new ArrayList<Path>();
//private String fileSorce="d:/test", fileDist="d:/dist";
private String fileSorce="/home/rsync", fileDist="/home/rsync/inbound/";
//-----"/home/rsync/"-----"/home/rsync/inbound/"-----
Logger log, logDeb;
private int ei, keyJob, reciveFileCount;
private Socket socket;
//private FileOutputStream fout;
private InputStream in;
private OutputStream out;
//private FileInputStream fin;
private DataInputStream din;
private DataOutputStream dout;
private String fIn,fOut, clientName;
private PrintWriter outS;
private long fileS;
private byte[] buffer = new byte[64*1024];
private Path pout;
public ServerClientConn(Socket sock, Logger lg, Logger logDeb) throws IOException {
//PropertyConfigurator.configure("src/log4j.properties");
socket=sock;
this.log=lg;
this.logDeb=logDeb;
din=new DataInputStream(socket.getInputStream());
dout=new DataOutputStream(socket.getOutputStream());
outS=new PrintWriter(socket.getOutputStream(),true);
}
@Override
public void run() {
try
{
clientName = din.readUTF();
logDeb.debug("Клиент - "+clientName);
//------------------------получаем сценарий работы
keyJob=din.read();
logDeb.debug(clientName+" Сценарий работы - "+keyJob);
//------------------------получаем сценарий работы
}catch(IOException e){logDeb.debug(clientName+" Не могу передать имя клиента");}
//------------------------Сценарий работы 1
if (keyJob==1){
logDeb.debug(clientName+" Сценарий работы 1");
reciveFileList();
copyFileTo();
try
{
copyFileFrom();
}catch(IOException ex){}
try
{
try {
in.close();
}catch(NullPointerException ein){}
try{
out.close();
}catch(NullPointerException eout){}
try{
din.close();
}catch(NullPointerException edin){}
try{
dout.close();
}catch(NullPointerException edout){}
try{
outS.close();
}catch(NullPointerException eoutS){}
try{
socket.close();
}catch(NullPointerException eoutS){}
}catch(IOException e){
logDeb.debug(clientName+" Ошибка закрытия сокета и потоков сценария 1");
log.error(clientName+" connection problem");
}
}
//------------------------Сценарий работы 1
//------------------------Сценарий работы 0
if (keyJob==0){
try{
logDeb.debug(clientName+" Сценарий работы 0");
sendFilesList();
}catch(IOException ex){}
}
//------------------------Сценарий работы 0
try{
try {
in.close();
}catch(NullPointerException ein){}
try{
out.close();
}catch(NullPointerException eout){}
try{
din.close();
}catch(NullPointerException edin){}
try{
dout.close();
}catch(NullPointerException edout){}
try{
outS.close();
}catch(NullPointerException eoutS){}
try{
socket.close();
}catch(NullPointerException eoutS){}
}catch(IOException exc){logDeb.debug(clientName +"Ошибка закрытия сокета и потоков сценария 0");}
logDeb.debug(clientName+"Завершил подключение");
}
private void copyFileTo(){
try
{
int filesCount=din.readInt();
//area.setText("Передается " + filesCount + " файлов\n");
logDeb.debug(clientName +" Передается " + filesCount + " файлов\n");
for (int i =0; i<filesCount; i++){
ei=i;
logDeb.debug(clientName+" Ожидание получения размера файла");
fileS=din.readLong();
logDeb.debug(clientName+" Ожидание получения имени файла");
fIn=din.readUTF();
logDeb.debug(clientName+" Пытаюсь скопировать файл "+fIn+" размер - "+fileS);
//fout=new FileOutputStream("/home/rsync/inbound/"+fIn);
//pout=Paths.get("/home/rsync/inbound/"+fIn);
pout=Paths.get(fileDist+fIn);
out=Files.newOutputStream(pout);
//fout=new FileOutputStream("D:/dist/"+fIn);
int count, total=0;
if (fileS>0){
while((count = din.read(buffer)) != -1){
total += count;
out.write(buffer, 0, count);
if(total == fileS){
logDeb.debug(clientName+" Копирование файла завершено"+fIn);
outS.println(fIn);
break;
}
}
}
if (fileS==0){
logDeb.debug(clientName + "Копирование файла 0-го размера безсмысленно и безпощадно");
outS.println(fIn);
}
log.info(clientName+" - received - "+fIn+" size="+fileS);
log.debug(clientName+" - received - "+fIn+" size="+fileS);
System.out.println(fIn);
out.close();
}
}catch(IOException e){
logDeb.debug(clientName+" Не могу скопировать файл"+fIn);
log.error(clientName +" - problem receive a file - "+ fIn);
outS.println("ERROR");
}
}
private void reciveFileList(){
//listFilesTransfer
try{
reciveFileCount=din.read();
for(int i=0; i<reciveFileCount; i++){
listFilesTransfer.add(Paths.get(fileSorce+"/"+clientName+"/"+din.readUTF()));
//System.out.println(listFilesTransfer.get(i).toString());
logDeb.debug(clientName +" "+listFilesTransfer.get(i).toString()+" "+Files.exists(listFilesTransfer.get(i)));
}
}catch(IOException e){logDeb.debug(clientName+ " Ошибка формирования списка передачи");}
}
private void sendFilesList() throws IOException{
// String src = "/home/rsync/", str = null,name;
String src, str = null,name;
//----------------------------Читаем директорию через Files и создаем масив Путей для файлов которые меньше 50 мб
src = fileSorce;
Path source;
ArrayList<Path> fileList = new ArrayList<Path>();
source = Paths.get(src+"/"+clientName);
logDeb.debug(source.toString());
Files.newDirectoryStream(source);
for (Path path : Files.newDirectoryStream(source)) {
if (!Files.isDirectory(path)){
if (Files.size(path)<52428800){
//System.out.println(path.toString());
fileList.add(Paths.get(path.toString()));
}
}
}
//System.out.println("sendFilesList");
//outS=new PrintWriter(socket.getOutputStream(), true);
dout.write(fileList.size());
logDeb.debug(clientName+" Передан размер");
for(int i = 0; i<fileList.size(); i++){
//System.out.println(fileList.get(i).toString()+" "+Files.size(fileList.get(i)));
dout.writeUTF(fileList.get(i).getFileName().toString());
//dout.writeLong(Files.size(fileList.get(i)));
}
outS.close();
dout.close();
}
private void copyFileFrom()throws IOException{
//String src = "/home/rsync/", str = null,name;
String src, str = null,name;
src = fileSorce;
//----------------------------Читаем директорию через Files и создаем масив Путей для файлов которые меньше 50 мб
Path source;
ArrayList<Path> fileList = listFilesTransfer;
/*ArrayList<Path> fileList = new ArrayList<Path>();
source = Paths.get(src+"/"+clientName);
Files.newDirectoryStream(source);
for (Path path : Files.newDirectoryStream(source)) {
if (!Files.isDirectory(path)){
if (Files.size(path)<52428800){
fileList.add(Paths.get(path.toString()));
}
}
}
for(int i = 0; i<fileList.size(); i++){
System.out.println(fileList.get(i).toString()+" "+Files.size(fileList.get(i)));
} */
//----------------------------Читаем директорию через Files и создаем масив Путей для файлов которые меньше 50 мб
int fileCnt, byteCnt;
fileCnt = fileList.size();
//System.out.println(fileCnt);
try{
dout = new DataOutputStream(socket.getOutputStream());
dout.writeInt(fileCnt);
logDeb.debug(clientName +" *************************************************************************");
for(int i=0; i<fileList.size(); i++){
logDeb.debug(clientName +" файл: " + fileList.get(i).toString());
dout.writeUTF(fileList.get(i).getFileName().toString());
dout.writeLong(Files.size(fileList.get(i)));
logDeb.debug(clientName+" длиной: " + Files.size(fileList.get(i)));
in=Files.newInputStream(fileList.get(i));
//while((byteCnt=fin.read(buffer))!=-1){
while((byteCnt=in.read(buffer))!=-1){
dout.write(buffer, 0, byteCnt);
}
dout.flush();
str = din.readUTF();
in.close();
//Files.delete(fileList.get(i));
log.info(clientName+" - sent - " +fileList.get(i).getFileName().toString() + " size "+Files.size(fileList.get(i)));
logDeb.debug(clientName +"получил файл: " + str + "\n*************************************************************************");
if (Files.deleteIfExists(fileList.get(i))) System.out.println("File "+fileList.get(i).getFileName()+" delete");
else logDeb.debug(clientName +" File "+fileList.get(i).getFileName()+" not delete");
}
}
catch(IOException e){
logDeb.debug(clientName +" Ошибка передачи " + e);
log.error(clientName+" problem receiving file" + str);
}
}
}
За код строго не судите только учусь.
|
|
|