You are on page 1of 14

Ministerul Educaţiei, Culturii și Cercetării al Republicii

Moldova

Universitatea Tehnică a Moldovei

Departamentul Informatică și Ingineria Sistemelor

RAPORT
Lucrare de laborator nr.7
Programarea concurenta si distribuita

A efectuat:
st. gr. CR-182 Dutca Alexandru

A verificat:
lect. univ. Rotaru Lilia

Chişinău – 2020
Lucrare de laborator nr. 7
1. Tema lucrării:
Programarea reţelelor cu ajutorul thread-urilor

2. Scopul lucrării:
Însuşirea metodelor de utilizarea thread-urilor pentru aplicaţiile client-server

3. Etapele de realizare:

1) Utilizarea clasei Thread pentru crearea unei clase noi;


2) Utilizarea interfeţei Runnable pentru crearea şi lansarea thread-urilor;
3) Crearea aplicaţiei client/server pentru un număr fixat de clienţi, utilizînd thread-urile;
4) Utilizarea interfeţei grafice pentru appleturile multi - user.
5) Exemplu de realizare:

Codul programului(Client(Main)):
package lab.six.Client.src.sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.Scanner;

public class Client extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
System.out.println("Nr.clienti: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0; i<n;i++){
_showWindow();
}
}

public static void main(String[] args) {


launch(args);
}

private void _showWindow() throws IOException {


Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root,530, 300);
stage.setTitle("Client-Server");
stage.setScene(scene);
stage.show();
stage.toFront();
}
}
(Controller.java):
package lab.six.Client.src.sample;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Controller {

public Button check;


public TextField id;
public TextField pass;
private static final int Server_PORT=9090;
private static final String Server_IP="127.0.0.1";
Socket socket;
PrintWriter out;
BufferedReader get_response;
String response_On_Check_User;

public void initialize() throws IOException {


socket=new Socket((Server_IP),Server_PORT);
}

public void check_Button_Click(javafx.event.ActionEvent actionEvent)


throws IOException {
out = new PrintWriter(socket.getOutputStream(), true);
out.println("check_user,"+verify());
get_response=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
response_On_Check_User=get_response.readLine();
System.out.println(response_On_Check_User);
id.clear();
pass.clear();
if(isStringInt(response_On_Check_User)){
sendData(actionEvent);
}
}

public String verify(){


String st1=pass.getText();
String st2=id.getText();
return st2+","+st1;
}

@FXML
private void sendData(javafx.event.ActionEvent event) {
// Step 1
User u = new User();
u.setGet_response(get_response);
u.setId_of_user(response_On_Check_User);
u.setOut(out);
u.setSocket(socket);
// Step 2
Node node = (Node) event.getSource();
// Step 3
Stage stage = (Stage) node.getScene().getWindow();
stage.close();
try {
// Step 4
Parent root = FXMLLoader.load(getClass().getResource("after_login.fxml"));
// Step 5
stage.setUserData(u);
// Step 6
Scene scene = new Scene(root);
stage.setScene(scene);
// Step 7
stage.show();
} catch (IOException e) {
System.err.println(String.format("Error: %s", e.getMessage()));
}
}
public boolean isStringInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}

static class User{


Socket socket;
String id_of_user;
PrintWriter out;
BufferedReader get_response;

public void setSocket(Socket socket) {


this.socket = socket;
}
public void setId_of_user(String id_of_user) {
this.id_of_user = id_of_user;
}

public void setOut(PrintWriter out) {


this.out = out;
}

public void setGet_response(BufferedReader get_response) {


this.get_response = get_response;
}

public Socket getSocket() {


return socket;
}

public String getId_of_user() {


return id_of_user;
}

public PrintWriter getOut() {


return out;
}

public BufferedReader get_response() {


return get_response;
}
}
}
Sample.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<GridPane alignment="center" hgap="10" vgap="10"


xmlns="http://javafx.com/javafx/10.0.2-internal"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="lab.six.Client.src.sample.Controller">
<columnConstraints>
<ColumnConstraints />
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
</rowConstraints>
<children>
<AnchorPane prefHeight="271.0" prefWidth="262.0" GridPane.columnIndex="1">
<children>
<Button fx:id="check" layoutX="105.0" layoutY="210.0"
mnemonicParsing="false" onAction="#check_Button_Click" text="Check" />
<TextField fx:id="id" layoutX="14.0" layoutY="37.0" promptText="Insert
id" />
<TextField fx:id="pass" layoutX="14.0" layoutY="111.0"
promptText="Insert pass" />
</children>
</AnchorPane>
</children>
</GridPane>

After_login_controller.java:
package lab.six.Client.src.sample;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class after_login_controller {


public AnchorPane window;
public Button insertb;
public Button extractb;
public Button allOperationsb;
public TextField sending_info;

final ObservableList clear =


FXCollections.observableArrayList();
public ListView <String> listofoperations;
public Label sumLabel;
Socket socket;
PrintWriter out;
BufferedReader get_response;

@FXML
private void receiveData(javafx.event.ActionEvent event) {
// Step 1
Node node = (Node) event.getSource();
Stage stage = (Stage) node.getScene().getWindow();
// Step 2
Controller.User u = (Controller.User) stage.getUserData();
// Step 3
socket = u.getSocket();
out=u.out;
get_response=u.get_response();
}

@FXML
private void insert(){
InsertTh th=new
InsertTh(sending_info,out,listofoperations,sumLabel,clear);
th.start();
}

@FXML
private void extract(){
ExtractTh th=new
ExtractTh(sending_info,out,listofoperations,sumLabel,clear);
th.start();
}

@FXML()
private void allOpereations() throws IOException {
allOperationsTh th=new
allOperationsTh(listofoperations,socket,out,get_response);
th.start();
}

@FXML
private void getSum() throws IOException {
out.println("getSum");
get_response=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String allOperations=get_response.readLine();
sumLabel.setText(allOperations);
}

public boolean isStringInt(String s)


{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}

class InsertTh extends Thread {


TextField sending_info;
PrintWriter out;
ListView <String> listofoperations;
Label sumLabel;
ObservableList clear;

public InsertTh(TextField sending_info,PrintWriter out, ListView <String>


listofoperations,Label sumLabel,ObservableList clear)
{this.clear=clear;
this.sumLabel=sumLabel;
this.listofoperations=listofoperations;
this.out=out;
this.sending_info=sending_info;
}

public void run(){


String textToSend= sending_info.getText();
if (isStringInt(textToSend)){
out.println("insert,"+ textToSend);
sending_info.clear();
Platform.runLater(()->{
listofoperations.setItems(clear);
});
Platform.runLater(()->{
sumLabel.setText("");
});;}else {
Platform.runLater(()->{
sumLabel.setText("wrong input");
});
}
}
}

class ExtractTh extends Thread {


TextField sending_info;
PrintWriter out;
ListView<String> listofoperations;
Label sumLabel;
ObservableList clear;

public ExtractTh(TextField sending_info, PrintWriter out, ListView<String>


listofoperations, Label sumLabel, ObservableList clear) {
this.clear = clear;
this.sumLabel = sumLabel;
this.listofoperations = listofoperations;
this.out = out;
this.sending_info = sending_info;
}

public void run(){


String textToSend= sending_info.getText();
if (isStringInt(textToSend)){
out.println("extract,"+ textToSend);
sending_info.clear();
Platform.runLater(()->{
listofoperations.setItems(clear);
});
Platform.runLater(()->{
sumLabel.setText("");
});
}else {
Platform.runLater(()->{
sumLabel.setText("wrong input");
});
}
}
}
class allOperationsTh extends Thread{
ListView <String> listofoperations;
Socket socket;
PrintWriter out;
BufferedReader get_response;
public allOperationsTh( ListView <String> listofoperations,Socket
socket,PrintWriter out,BufferedReader get_response)
{this.listofoperations=listofoperations;
this.socket=socket;
this.out=out;
this.get_response=get_response;
}

public void run(){


out.println("allOperations");
try {
get_response=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String allOperations= null;
try {
allOperations = get_response.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(allOperations);
String[] allOperationsArray = allOperations.split(",");
final ObservableList names =
FXCollections.observableArrayList();
for (String temp : allOperationsArray) {
names.add(temp);
}
Platform.runLater(()->{
listofoperations.setItems(names);
});
}
}

class getSumTh extends Thread{


Label sumLabel;
Socket socket;
PrintWriter out;
BufferedReader get_response;
public getSumTh( Label sumLabel,Socket socket,PrintWriter
out,BufferedReader get_response)
{
this.sumLabel=sumLabel;
this.socket=socket;
this.out=out;
this.get_response=get_response;
}

public void run(){


out.println("getSum");
try {
get_response=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String allOperations= null;
try {
allOperations = get_response.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String finalAllOperations = allOperations;
Platform.runLater(()->{
sumLabel.setText(finalAllOperations);
});
}
}
}
after_login.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="window" prefHeight="400.0" prefWidth="600.0"


xmlns="http://javafx.com/javafx/10.0.2-internal"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="lab.six.Client.src.sample.after_login_controller">
<children>
<Button fx:id="insertb" layoutX="160.0" layoutY="50.0"
mnemonicParsing="false" onAction="#insert" text="insert" />
<Button fx:id="extractb" layoutX="416.0" layoutY="50.0"
mnemonicParsing="false" onAction="#extract" text="extract" />
<Button fx:id="allOperationsb" layoutX="372.0" layoutY="95.0"
mnemonicParsing="false" onAction="#allOpereations" text="all operations" />
<TextField fx:id="sending_info" layoutX="233.0" layoutY="50.0" />
<Button layoutX="247.0" layoutY="2.0" mnemonicParsing="false"
onAction="#receiveData" prefHeight="25.0" prefWidth="69.0" text="connect" />
<ListView fx:id="listofoperations" layoutX="316.0" layoutY="129.0"
prefHeight="257.0" prefWidth="200.0" />
<Button layoutX="102.0" layoutY="95.0" mnemonicParsing="false"
onAction="#getSum" text="ballance" />
<Label fx:id="sumLabel" layoutX="67.0" layoutY="136.0" prefHeight="25.0"
prefWidth="130.0" />
</children>
</AnchorPane>

Server.java:
package lab.six.Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;

public class Server {


private static final int PORT = 9090;
static ArrayList<Users> list = new ArrayList<>();

public static void main(String[] args) throws IOException {


Users a = new Users("1", "qwe");
list.add(a);
Users b = new Users("2", "asd");
list.add(b);
Users c = new Users("3", "zxc");
list.add(c);

ServerSocket listener = new ServerSocket(PORT);

while (true){
System.out.println("wait for clients");
Socket client = listener.accept();
System.out.println("conected");
BufferedReader input=new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter out=new PrintWriter(client.getOutputStream(),true);
Server_Actions th=new Server_Actions(list, client, input, out);
th.start();
}

public static String login_validation(String id, String password) {


String answer = null;
for (Users current : list) {
boolean result=current.check(id, password);
if (result){
answer= String.valueOf(list.indexOf(current));
break;
}
answer="false";
}
return answer;
}

static class Server_Actions extends Thread{


ArrayList<Users> list;
Socket client;
BufferedReader input;
PrintWriter out;

public Server_Actions(ArrayList<Users> list, Socket client, BufferedReader


input, PrintWriter out) {
this.list = list;
this.client = client;
this.input = input;
this.out = out;
}

@Override
public void run() {
int sum=0;
String actions = "";
try {

while (true){

String what_To_Do= null;


try {
what_To_Do = input.readLine();
} catch (SocketException e) {
input.close();
out.close();
client.close();
}
if (what_To_Do==null){
break;
}
String[] request_and_info = what_To_Do.split(",");
System.out.println(what_To_Do=request_and_info[0]);

if(what_To_Do.equals("check_user")){
String respone = null;
try {
String check_id=request_and_info[1];
String check_password=request_and_info[2];
respone=login_validation(check_id, check_password);
} catch (ArrayIndexOutOfBoundsException e) {
respone="fields cannot be uncompletted";
}
System.out.println(respone);
out.println(respone);

}
if(what_To_Do.equals("insert")){
String forsum=request_and_info[1];
sum=sum+Integer.parseInt(forsum);
actions= actions + "+" + forsum + ",";
System.out.println(actions);
}
if(what_To_Do.equals("extract")){
String forsum=request_and_info[1];
sum=sum-Integer.parseInt(forsum);
actions= actions + "-" + forsum + ",";
System.out.println(actions);
}
if(what_To_Do.equals("allOperations")){
out.println(actions);
}
if(what_To_Do.equals("getSum")){
out.println(sum);
}
if(what_To_Do.equals("exit")){ break; }

}
}catch (NumberFormatException | IOException e){e.printStackTrace();}
}
}

static class Users {


private String id;
private String password;

public Users(String id, String password) {


this.id = id;
this.password = password;
}

public boolean check(String id, String password) {


if (id.equals(this.id)) {
return password.equals(this.password);
}
return false;
}
}

Rezultatul rularii:

You might also like