Guest User

Untitled

a guest
Nov 23rd, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.97 KB | None | 0 0
  1. public class LaptopServer {
  2. private static final String LOG_TAG = "myServerApp";
  3.  
  4. // ip адрес сервера, который принимает соединения
  5. private String mServerName = "192.168.1.88";
  6. // номер порта, на который сервер принимает соединения
  7. private int mServerPort = 8520;
  8. // сокет, через которий приложения общается с сервером
  9. private Socket mSocket = null;
  10.  
  11. public LaptopServer() {}
  12.  
  13. // Открытие нового соединения. Если сокет уже открыт, то он закрывается.
  14. //@throws Exception
  15. // Если не удалось открыть сокет
  16. public void openConnection() throws Exception {
  17.  
  18. // Освобождаем ресурсы
  19. closeConnection();
  20.  
  21. try {
  22. //Создаем новый сокет. Указываем на каком компютере и порту запущен наш процесс,
  23. //который будет принамать наше соединение.
  24. mSocket = new Socket(mServerName,mServerPort);
  25.  
  26. } catch (IOException e) {
  27. throw new Exception("Невозможно создать сокет: "+e.getMessage());
  28. }
  29. }
  30.  
  31. //Метод для закрытия сокета, по которому мы общались.
  32. public void closeConnection(){
  33.  
  34. //Проверяем сокет. Если он не зарыт, то закрываем его и освобдождаем соединение.
  35. if (mSocket != null && !mSocket.isClosed()) {
  36.  
  37. try {
  38. mSocket.close();
  39. } catch (IOException e) {
  40. JOptionPane.showMessageDialog(null, "Невозможно закрыть сокет: " + e.getMessage());
  41. } finally {
  42. mSocket = null;
  43. }
  44.  
  45. }
  46. mSocket = null;
  47. }
  48.  
  49. //Метод для отправки данных по сокету.
  50. //@param data
  51. // Данные, которые будут отправлены
  52. //@throws Exception
  53. // Если невозможно отправить данные
  54. public void sendData(byte[] data) throws Exception {
  55.  
  56. /* Проверяем сокет. Если он не создан или закрыт, то выдаем исключение */
  57. if (mSocket == null || mSocket.isClosed()) {
  58. throw new Exception("Невозможно отправить данные. Сокет не создан или закрыт");
  59. }
  60.  
  61. /* Отправка данных */
  62. try {
  63. mSocket.getOutputStream().write(data);
  64. mSocket.getOutputStream().flush();
  65. } catch (IOException e) {
  66. throw new Exception("Невозможно отправить данные: "+e.getMessage());
  67. }
  68. }
  69.  
  70. //переопределить метод finalize() и освободить ресурс
  71. @Override
  72. protected void finalize() throws Throwable {
  73. super.finalize();
  74. closeConnection();
  75. }
  76. }
  77.  
  78. sendPlannedButton.addActionListener(new ActionListener() {
  79. @Override
  80. public void actionPerformed(ActionEvent e) {
  81. //выключаем кнопку
  82. sendPlannedButton.setEnabled(false);
  83. //создаем объект для работы с сервером
  84. mServer = new LaptopServer();
  85.  
  86. serverPass = "какой то пароль";
  87. sendPurchase = labelPurchase.getText();
  88. sendPurchase = sendPurchase.getBytes();
  89. Date date = new Date();
  90. sendDate = formatDate.format(date);
  91. sendName = logInName;
  92. sendEmail = logInEmail;
  93. sendNomenclature = new ArrayList<String>();
  94. sendNomenclature = selectNomenclaturePlanned;
  95. sendItem = new ArrayList<String>();
  96. sendItem = selectItemPlanned;
  97.  
  98. if (mServer == null) {
  99. JOptionPane.showMessageDialog(null, "Сервер не создан");
  100. }
  101.  
  102. //Открываем соединение. Открытие должно происходить в отдельном потоке
  103. new Thread(new Runnable() {
  104. @Override
  105. public void run() {
  106. try{
  107. mServer.openConnection();
  108. Thread.sleep(500);
  109. //отправляем на сервер данные
  110. mServer.sendData(serverPass.getBytes());
  111. Thread.sleep(200);
  112. mServer.sendData(sendPurchase.getBytes());
  113. Thread.sleep(200);
  114. mServer.sendData(sendDate.getBytes());
  115. Thread.sleep(200);
  116. mServer.sendData(sendName.getBytes());
  117. Thread.sleep(200);
  118. mServer.sendData(sendEmail.getBytes());
  119. Thread.sleep(200);
  120.  
  121. for (int i=0; i<sendNomenclature.size(); i++){
  122. mServer.sendData(sendNomenclature.get(i).getBytes());
  123. Thread.sleep(200);
  124. mServer.sendData(sendItem.get(i).getBytes());
  125. Thread.sleep(200);
  126. }
  127.  
  128. }catch (Exception e){
  129. JOptionPane.showMessageDialog(null, "Произошла ошибка при отправке");
  130. mServer = null;
  131. }
  132. //Закрываем соединение
  133. mServer.closeConnection();
  134. }
  135. }).start();
  136. }
  137. });
  138.  
  139. public class Server implements Runnable {
  140.  
  141. //Реалезация шаблона Singleton
  142. //{@link https://en.wikipedia.org/wiki/Singleton_pattern}
  143.  
  144. private static volatile Server instane = null;
  145.  
  146. //Порт, на который сервер принимает соеденения
  147. private final int SERVER_PORT = 8520;
  148. //Сокет, который обрабатывает соединения на сервере
  149. private static ServerSocket serverSoket = null;
  150.  
  151. private Server() {
  152. }
  153.  
  154. static Server getServer() {
  155.  
  156. if (instane == null) {
  157. synchronized (Server.class) {
  158. if (instane == null) {
  159. instane = new Server();
  160. }
  161. }
  162. }
  163. return instane;
  164. }
  165.  
  166. @Override
  167. public void run() {
  168. try {
  169. //Создаем серверный сокет, которые принимает соединения
  170. serverSoket = new ServerSocket(SERVER_PORT);
  171.  
  172. //старт приема соединений на сервер
  173. while(true) {
  174. ConnectionWorker worker = null;
  175. try {
  176. //ждем нового соединения
  177. worker = new ConnectionWorker(serverSoket.accept());
  178.  
  179. //создается новый поток, в котором обрабатывается соединение
  180. Thread t = new Thread(worker);
  181. t.start();
  182. } catch (Exception e) {
  183. MyFrame.journal = "<br>Connection error: "+e.getMessage();
  184. }
  185. }
  186. } catch (Exception e) {
  187. MyFrame.journal = "<br>I can not start the server on the port "+SERVER_PORT+":"+e.getMessage();
  188. }finally {
  189. //Закрываем соединение
  190. if (serverSoket != null) {
  191. try {
  192. serverSoket.close();
  193. } catch (IOException e) {
  194. MyFrame.journal = "<br>"+e.getMessage();
  195. }
  196. }
  197. }
  198. }
  199. }
  200.  
  201. public class ConnectionWorker implements Runnable{
  202.  
  203. //сокет, через который происходит обмен данными с клиентом
  204. private Socket clientSocket = null;
  205. //входной поток, через который получаем данные с сокета
  206. private InputStream inputStream = null;
  207.  
  208.  
  209. private String pass="какой то пароль";
  210. private String name;
  211. private String purchase;
  212. private String date;
  213. private String textNomenclature;
  214. private String textAddress;
  215. private String textRegNum;
  216. private String textComment;
  217. private ArrayList<String> nomenclature = new ArrayList<String>();
  218. private ArrayList<Integer> metr = new ArrayList<Integer>();
  219. private ArrayList<Integer> items = new ArrayList<Integer>();
  220. private ArrayList<String> address = new ArrayList<String>();
  221. private ArrayList<String> regNum = new ArrayList<String>();
  222. private ArrayList<String> comment = new ArrayList<String>();
  223. private ArrayList<String> excelNomenclature;
  224.  
  225. private int num=0;
  226. private int numUrgent=0;
  227. private Path path;
  228. private String textPath = "какой то путь";
  229. private String textDatePath = "";
  230.  
  231.  
  232.  
  233. ConnectionWorker(Socket socket) {
  234. clientSocket = socket;
  235. }
  236.  
  237. @Override
  238. public void run() {
  239. //получаем входной поток
  240. try {
  241. inputStream = clientSocket.getInputStream();
  242. } catch (IOException e) {
  243. MyFrame.journal = "<br>Do not get the input stream";
  244. }
  245.  
  246. //создаем буфер для данных
  247. byte[] buffer = new byte[1024 * 4];
  248.  
  249. while (true) {
  250. try {
  251. //получаем очередную порцию данных
  252. //в переменной count хранится реальное количество байт, которое получили
  253. int count = inputStream.read(buffer, 0, buffer.length);
  254.  
  255. //проверяем, какое количество байт к нам прийшло
  256. if (count > 0) {
  257.  
  258. if (num==0){
  259. if (!(new String(buffer,0,count).equals(pass))){
  260. MyFrame.journal = "<br>Unauthorized connection<br>close socket";
  261. MyFrame.journalLabel += MyFrame.journal;
  262. MyFrame.journalLabelUpdate();
  263. MyFrame.journalUpdate();
  264. clientSocket.close();
  265. num=0;
  266. break;
  267. }else{
  268. MyFrame.journal = "<br>Password confirmed";
  269. MyFrame.journalLabel += MyFrame.journal;
  270. MyFrame.journalLabelUpdate();
  271. MyFrame.journalUpdate();
  272. num++;
  273. }
  274. }
  275. else if (num==1){
  276. purchase = new String(buffer, 0, count);
  277. purchase = new String(purchase.getBytes(),"UTF-8");
  278. num++;
  279. MyFrame.journal = "<br> Purchase: "+purchase;
  280. MyFrame.journalLabel += MyFrame.journal;
  281. MyFrame.journalLabelUpdate();
  282. MyFrame.journalUpdate();
  283. }
  284. else if (num==2){
  285. date = new String(buffer, 0, count);
  286. date = new String(date.getBytes(),"UTF-8");
  287. String testDate = date.substring(8);
  288. int testDateNum = Integer.parseInt(testDate);
  289. if (testDateNum>19){
  290. testDate = date.substring(5,7);
  291. testDateNum = Integer.parseInt(testDate)+1;
  292. textDatePath = new String(buffer, 0, 5);
  293. textDatePath += Integer.toString(testDateNum);
  294. }else{
  295. textDatePath = new String(buffer, 0, 7);
  296. }
  297. num++;
  298. MyFrame.journal = "<br> Date: "+date + "<br> Direct: " + textDatePath;
  299. }
  300. else if (num==3){
  301. name = new String(buffer, 0, count);
  302. name = new String(name.getBytes(),"UTF-8");
  303. num++;
  304. MyFrame.journal = "<br> Sender: "+name;
  305. }
  306. else if (num==4){
  307. email = new String(buffer, 0, count);
  308. email = new String(email.getBytes(),"UTF-8");
  309. num++;
  310. MyFrame.journal = "<br> Sender Email: "+ email;
  311. }
  312. else if (num>4 && purchase.equals("Плановая закупка")){
  313. if (!(num%2==0)){
  314. textNomenclature = new String(buffer, 0, count);
  315. textNomenclature = new String(textNomenclature.getBytes(), "UTF-8");
  316. nomenclature.add(textNomenclature);
  317.  
  318. MyFrame.journal = "<br> Num: "+ num;
  319. num++;
  320. } else{
  321. items.add(Integer.parseInt(new String(buffer, 0, count)));
  322. num++;
  323. }
  324. }
  325. else if (num>4 && purchase.equals("Срочная закупка")){
  326. if (numUrgent==0 || numUrgent%6==0){
  327. textNomenclature = new String(buffer, 0, count);
  328. textNomenclature = new String(textNomenclature.getBytes(), "UTF-8");
  329. nomenclature.add(textNomenclature);
  330. numUrgent++;
  331. num++;
  332. }
  333. else if (numUrgent==1 || (numUrgent-1)%6==0){
  334. metr.add(Integer.parseInt(new String(buffer, 0, count)));
  335. numUrgent++;
  336. num++;
  337. }
  338. else if (numUrgent==2 || (numUrgent-2)%6==0){
  339. items.add(Integer.parseInt(new String(buffer, 0, count)));
  340. numUrgent++;
  341. num++;
  342. }
  343. else if (numUrgent==3 || (numUrgent-3)%6==0){
  344. textAddress = new String(buffer, 0, count);
  345. textAddress = new String(textAddress.getBytes(), "UTF-8");
  346. address.add(textAddress);
  347. numUrgent++;
  348. num++;
  349. }
  350. else if (numUrgent==4 || (numUrgent-4)%6==0){
  351. textRegNum = new String(buffer, 0, count);
  352. textRegNum = new String(textRegNum.getBytes(), "UTF-8");
  353. regNum.add(textRegNum);
  354. numUrgent++;
  355. num++;
  356. }
  357. else if (numUrgent==5 || (numUrgent-5)%6==0){
  358. textComment = new String(buffer, 0, count);
  359. textComment = new String(textComment.getBytes(), "UTF-8");
  360. comment.add(textComment);
  361. numUrgent++;
  362. num++;
  363. }
  364. }
  365. }else
  366. //если мы получили -1, значит прервался наш поток с данными
  367. if (count == -1 ) {
  368. MyFrame.journal = "<br>close socket";
  369. clientSocket.close();
  370. break;
  371. }
  372. } catch (IOException e) {
  373. MyFrame.journal = "<br>"+e.getMessage();
  374. }
  375. }
  376. }
Add Comment
Please, Sign In to add comment