Java Socket passing a class object from the client to the server
I'm studying Java Socket and the client server part, I don't understand the moment of transferring the class object (names and values of variables for performing calculations) from the client to the server, I Googled it and decided to try transmitting it via json. There is a class
public class CalculatorModel
{
private String JSON;
private double number;
private double sizeCredit;
// Конструктор
public CalculatorModel(number, sizeCredit)
{
this.number=number;
this. sizeCredit = sizeCredit;
}
// У него метод читающий данные из csv файла и кидающий их в лист
public void readFile() throws IOException
// Метод инициализации данных
public void initialization()
{
for(int i=0; i<value.size(); i++)
{
number = value.get(i);
sizeCredit = value.get(i+1)
Gson gson = new Gson();
JSON = gson.toJson(new CalculatorModel(number, sizeCredit));
}
}
// Метод производит вычисления и бросает данные в лист
calculation throws IOException ();
{
Возвращает List<String> exitData
}
}
Client
public class CalculatorClientIO implements Runnable
{
@Override
public void run()
{
int serverPort=8080;
String adress="127.0.0.1";
try
{
Socket socket = new Socket(adress, serverPort);
System.out.println("Устанавливаем соединение");
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write ????????;
out.flush();
String line = in.readUTF();
System.out.println("Сервер ответил: " + line);
}
catch(Exception er)
{
er.printStackTrace();
}
}
}
Server
public class CalculatorServerIO
{
public static void main(String[] args)
{
int port=8080;
CalculatorClientIO se=new CalculatorClientIO();
Thread th=new Thread(se);
th.start();
try
{
ServerSocket ss = new ServerSocket(port);
while(true)
{
Socket socket = ss.accept();
System.out.println("Есть контакт !");
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String line = in.read ??????;
System.out.println("Клиент прислал : " + line);
System.out.println("Отправляем ему в ответ: );
out.write??????;
out.flush();
}
}
catch(Exception er)
{
er.printStackTrace();
}
}
}
0
Author: Alexander Chernin, 2020-02-01
1 answers
To send java objects, use ObjectInputStream
and ObjectOutputStream
.
They have methods readObject
, writeObject
accordingly. The objects will be serialized to bytes and back.
Only the class must implement the Serializable
interface.
0
Author: Tix, 2020-02-02 17:07:41