Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LaptopServer {
- private static final String LOG_TAG = "myServerApp";
- // ip адрес сервера, который принимает соединения
- private String mServerName = "192.168.1.88";
- // номер порта, на который сервер принимает соединения
- private int mServerPort = 8520;
- // сокет, через которий приложения общается с сервером
- private Socket mSocket = null;
- public LaptopServer() {}
- // Открытие нового соединения. Если сокет уже открыт, то он закрывается.
- //@throws Exception
- // Если не удалось открыть сокет
- public void openConnection() throws Exception {
- // Освобождаем ресурсы
- closeConnection();
- try {
- //Создаем новый сокет. Указываем на каком компютере и порту запущен наш процесс,
- //который будет принамать наше соединение.
- mSocket = new Socket(mServerName,mServerPort);
- } catch (IOException e) {
- throw new Exception("Невозможно создать сокет: "+e.getMessage());
- }
- }
- //Метод для закрытия сокета, по которому мы общались.
- public void closeConnection(){
- //Проверяем сокет. Если он не зарыт, то закрываем его и освобдождаем соединение.
- if (mSocket != null && !mSocket.isClosed()) {
- try {
- mSocket.close();
- } catch (IOException e) {
- JOptionPane.showMessageDialog(null, "Невозможно закрыть сокет: " + e.getMessage());
- } finally {
- mSocket = null;
- }
- }
- mSocket = null;
- }
- //Метод для отправки данных по сокету.
- //@param data
- // Данные, которые будут отправлены
- //@throws Exception
- // Если невозможно отправить данные
- public void sendData(byte[] data) throws Exception {
- /* Проверяем сокет. Если он не создан или закрыт, то выдаем исключение */
- if (mSocket == null || mSocket.isClosed()) {
- throw new Exception("Невозможно отправить данные. Сокет не создан или закрыт");
- }
- /* Отправка данных */
- try {
- mSocket.getOutputStream().write(data);
- mSocket.getOutputStream().flush();
- } catch (IOException e) {
- throw new Exception("Невозможно отправить данные: "+e.getMessage());
- }
- }
- //переопределить метод finalize() и освободить ресурс
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- closeConnection();
- }
- }
- sendPlannedButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- //выключаем кнопку
- sendPlannedButton.setEnabled(false);
- //создаем объект для работы с сервером
- mServer = new LaptopServer();
- serverPass = "какой то пароль";
- sendPurchase = labelPurchase.getText();
- sendPurchase = sendPurchase.getBytes();
- Date date = new Date();
- sendDate = formatDate.format(date);
- sendName = logInName;
- sendEmail = logInEmail;
- sendNomenclature = new ArrayList<String>();
- sendNomenclature = selectNomenclaturePlanned;
- sendItem = new ArrayList<String>();
- sendItem = selectItemPlanned;
- if (mServer == null) {
- JOptionPane.showMessageDialog(null, "Сервер не создан");
- }
- //Открываем соединение. Открытие должно происходить в отдельном потоке
- new Thread(new Runnable() {
- @Override
- public void run() {
- try{
- mServer.openConnection();
- Thread.sleep(500);
- //отправляем на сервер данные
- mServer.sendData(serverPass.getBytes());
- Thread.sleep(200);
- mServer.sendData(sendPurchase.getBytes());
- Thread.sleep(200);
- mServer.sendData(sendDate.getBytes());
- Thread.sleep(200);
- mServer.sendData(sendName.getBytes());
- Thread.sleep(200);
- mServer.sendData(sendEmail.getBytes());
- Thread.sleep(200);
- for (int i=0; i<sendNomenclature.size(); i++){
- mServer.sendData(sendNomenclature.get(i).getBytes());
- Thread.sleep(200);
- mServer.sendData(sendItem.get(i).getBytes());
- Thread.sleep(200);
- }
- }catch (Exception e){
- JOptionPane.showMessageDialog(null, "Произошла ошибка при отправке");
- mServer = null;
- }
- //Закрываем соединение
- mServer.closeConnection();
- }
- }).start();
- }
- });
- public class Server implements Runnable {
- //Реалезация шаблона Singleton
- //{@link https://en.wikipedia.org/wiki/Singleton_pattern}
- private static volatile Server instane = null;
- //Порт, на который сервер принимает соеденения
- private final int SERVER_PORT = 8520;
- //Сокет, который обрабатывает соединения на сервере
- private static ServerSocket serverSoket = null;
- private Server() {
- }
- static Server getServer() {
- if (instane == null) {
- synchronized (Server.class) {
- if (instane == null) {
- instane = new Server();
- }
- }
- }
- return instane;
- }
- @Override
- public void run() {
- try {
- //Создаем серверный сокет, которые принимает соединения
- serverSoket = new ServerSocket(SERVER_PORT);
- //старт приема соединений на сервер
- while(true) {
- ConnectionWorker worker = null;
- try {
- //ждем нового соединения
- worker = new ConnectionWorker(serverSoket.accept());
- //создается новый поток, в котором обрабатывается соединение
- Thread t = new Thread(worker);
- t.start();
- } catch (Exception e) {
- MyFrame.journal = "<br>Connection error: "+e.getMessage();
- }
- }
- } catch (Exception e) {
- MyFrame.journal = "<br>I can not start the server on the port "+SERVER_PORT+":"+e.getMessage();
- }finally {
- //Закрываем соединение
- if (serverSoket != null) {
- try {
- serverSoket.close();
- } catch (IOException e) {
- MyFrame.journal = "<br>"+e.getMessage();
- }
- }
- }
- }
- }
- public class ConnectionWorker implements Runnable{
- //сокет, через который происходит обмен данными с клиентом
- private Socket clientSocket = null;
- //входной поток, через который получаем данные с сокета
- private InputStream inputStream = null;
- private String pass="какой то пароль";
- private String name;
- private String purchase;
- private String date;
- private String textNomenclature;
- private String textAddress;
- private String textRegNum;
- private String textComment;
- private ArrayList<String> nomenclature = new ArrayList<String>();
- private ArrayList<Integer> metr = new ArrayList<Integer>();
- private ArrayList<Integer> items = new ArrayList<Integer>();
- private ArrayList<String> address = new ArrayList<String>();
- private ArrayList<String> regNum = new ArrayList<String>();
- private ArrayList<String> comment = new ArrayList<String>();
- private ArrayList<String> excelNomenclature;
- private int num=0;
- private int numUrgent=0;
- private Path path;
- private String textPath = "какой то путь";
- private String textDatePath = "";
- ConnectionWorker(Socket socket) {
- clientSocket = socket;
- }
- @Override
- public void run() {
- //получаем входной поток
- try {
- inputStream = clientSocket.getInputStream();
- } catch (IOException e) {
- MyFrame.journal = "<br>Do not get the input stream";
- }
- //создаем буфер для данных
- byte[] buffer = new byte[1024 * 4];
- while (true) {
- try {
- //получаем очередную порцию данных
- //в переменной count хранится реальное количество байт, которое получили
- int count = inputStream.read(buffer, 0, buffer.length);
- //проверяем, какое количество байт к нам прийшло
- if (count > 0) {
- if (num==0){
- if (!(new String(buffer,0,count).equals(pass))){
- MyFrame.journal = "<br>Unauthorized connection<br>close socket";
- MyFrame.journalLabel += MyFrame.journal;
- MyFrame.journalLabelUpdate();
- MyFrame.journalUpdate();
- clientSocket.close();
- num=0;
- break;
- }else{
- MyFrame.journal = "<br>Password confirmed";
- MyFrame.journalLabel += MyFrame.journal;
- MyFrame.journalLabelUpdate();
- MyFrame.journalUpdate();
- num++;
- }
- }
- else if (num==1){
- purchase = new String(buffer, 0, count);
- purchase = new String(purchase.getBytes(),"UTF-8");
- num++;
- MyFrame.journal = "<br> Purchase: "+purchase;
- MyFrame.journalLabel += MyFrame.journal;
- MyFrame.journalLabelUpdate();
- MyFrame.journalUpdate();
- }
- else if (num==2){
- date = new String(buffer, 0, count);
- date = new String(date.getBytes(),"UTF-8");
- String testDate = date.substring(8);
- int testDateNum = Integer.parseInt(testDate);
- if (testDateNum>19){
- testDate = date.substring(5,7);
- testDateNum = Integer.parseInt(testDate)+1;
- textDatePath = new String(buffer, 0, 5);
- textDatePath += Integer.toString(testDateNum);
- }else{
- textDatePath = new String(buffer, 0, 7);
- }
- num++;
- MyFrame.journal = "<br> Date: "+date + "<br> Direct: " + textDatePath;
- }
- else if (num==3){
- name = new String(buffer, 0, count);
- name = new String(name.getBytes(),"UTF-8");
- num++;
- MyFrame.journal = "<br> Sender: "+name;
- }
- else if (num==4){
- email = new String(buffer, 0, count);
- email = new String(email.getBytes(),"UTF-8");
- num++;
- MyFrame.journal = "<br> Sender Email: "+ email;
- }
- else if (num>4 && purchase.equals("Плановая закупка")){
- if (!(num%2==0)){
- textNomenclature = new String(buffer, 0, count);
- textNomenclature = new String(textNomenclature.getBytes(), "UTF-8");
- nomenclature.add(textNomenclature);
- MyFrame.journal = "<br> Num: "+ num;
- num++;
- } else{
- items.add(Integer.parseInt(new String(buffer, 0, count)));
- num++;
- }
- }
- else if (num>4 && purchase.equals("Срочная закупка")){
- if (numUrgent==0 || numUrgent%6==0){
- textNomenclature = new String(buffer, 0, count);
- textNomenclature = new String(textNomenclature.getBytes(), "UTF-8");
- nomenclature.add(textNomenclature);
- numUrgent++;
- num++;
- }
- else if (numUrgent==1 || (numUrgent-1)%6==0){
- metr.add(Integer.parseInt(new String(buffer, 0, count)));
- numUrgent++;
- num++;
- }
- else if (numUrgent==2 || (numUrgent-2)%6==0){
- items.add(Integer.parseInt(new String(buffer, 0, count)));
- numUrgent++;
- num++;
- }
- else if (numUrgent==3 || (numUrgent-3)%6==0){
- textAddress = new String(buffer, 0, count);
- textAddress = new String(textAddress.getBytes(), "UTF-8");
- address.add(textAddress);
- numUrgent++;
- num++;
- }
- else if (numUrgent==4 || (numUrgent-4)%6==0){
- textRegNum = new String(buffer, 0, count);
- textRegNum = new String(textRegNum.getBytes(), "UTF-8");
- regNum.add(textRegNum);
- numUrgent++;
- num++;
- }
- else if (numUrgent==5 || (numUrgent-5)%6==0){
- textComment = new String(buffer, 0, count);
- textComment = new String(textComment.getBytes(), "UTF-8");
- comment.add(textComment);
- numUrgent++;
- num++;
- }
- }
- }else
- //если мы получили -1, значит прервался наш поток с данными
- if (count == -1 ) {
- MyFrame.journal = "<br>close socket";
- clientSocket.close();
- break;
- }
- } catch (IOException e) {
- MyFrame.journal = "<br>"+e.getMessage();
- }
- }
- }
Add Comment
Please, Sign In to add comment