In my program, the client and server interact with each other using text commands that are moved using streams, but when I send a command, the server does not perceive it and freezes tightly. When debugging, I found out that messages are not sent through streams. In this case there are no errors.

In the server logs found such a record, maybe the point is this.

INFO: HHH000206: hibernate.properties not found 

DAO.java

  package DataBase.Dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Рабочий on 20.04.2016. */ // Основа классов для работы с базой данных public class DAO { private static final Logger log = Logger.getAnonymousLogger(); private static final ThreadLocal session = new ThreadLocal(); private static final SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory(); protected DAO(){ } //Метод для работы с сессиями public static Session getSession() { Session session = (Session) DAO.session.get(); if (session == null) { session = sessionfactory.openSession(); DAO.session.set(session); } return session; } //Начать транзакцию protected void begin(){ getSession().beginTransaction(); } //Подтвердить изменение protected void commit(){ getSession().getTransaction().commit(); } //Откат изменений в случае сбоев protected void rollback(){ try{ getSession().getTransaction().rollback(); } catch (HibernateException e){ log.log(Level.WARNING,"Cannot rollback",e); } try{ getSession().close(); } catch (HibernateException e){ log.log(Level.WARNING,"Cannot close",e); } DAO.session.set(null); } //Закрыть сессию protected void close(){ getSession().close(); DAO.session.set(null); } } 

Students.java

  package DataBase.Dao; import DataBase.Tables.Students; import org.hibernate.HibernateException; import org.hibernate.Query; import java.util.Iterator; import java.util.List; /** * Created by Рабочий on 20.04.2016. */ //DAO для работы со студентами public class StudentsDAO extends DAO { //Создать студента public Students createStudent(String Firstname,String Lastname, String Group) throws Exception { try { begin(); Students students = new Students(Firstname,Lastname,Group); getSession().save(students); commit(); close(); return students; } catch (HibernateException e) { rollback(); throw new Exception("Could not create student " + " ", e); } } public List<Students> retrieveAllStudent() throws Exception{ try { begin(); List<Students> students = getSession().createQuery("from Students ").list(); commit(); close(); return students; } catch (HibernateException e){ rollback(); throw new Exception("Could not get students" + e ); } } public void updateStudent(int studentId,String FirstName,String LastName, String Group) throws Exception { try { begin(); Students stud =(Students)getSession().get(Students.class,studentId); stud.setFirstName(FirstName); stud.setLastName(LastName); stud.setGroup(Group); getSession().update(stud); commit(); close(); } catch (HibernateException e){ rollback(); try { throw new Exception("Could not update student " + studentId); } catch (Exception e1) { e1.printStackTrace(); } } } //Удалить студента public void deleteStudent(int studentid) throws Exception{ try { begin(); Students stud = (Students) getSession().get(Students.class,studentid); getSession().delete(stud); commit(); close(); } catch (HibernateException e){ rollback(); throw new Exception("Could not delete student " + studentid); } } } 

Server.java

 package DataBase.Server; import DataBase.Dao.StudentsDAO; import DataBase.Tables.Students; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Iterator; import java.util.List; /** * Created by Рабочий on 17.04.2016. */ public class Server { private static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); private static Session session; private static Transaction tx; public static boolean checkstud(String finame,String laname,String gro){ session = sessionFactory.openSession(); tx = session.beginTransaction(); List students = session.createQuery("from Students ").list(); for (Iterator iterator = students.iterator();iterator.hasNext();){ Students stud = (Students) iterator.next(); if(finame.equals(stud.getFirstName())&&laname.equals(stud.getLastName())&&gro.equals(stud.getGroup())){ return false; } } return true; } public static void main(String[] args) { int port = 5555; //Серверный порт try { ServerSocket sv = new ServerSocket(port); System.out.println("Waiting for a client"); Socket sock = sv.accept(); System.out.println("Client is ready!"); System.out.println(); boolean checkCopy=false; StudentsDAO studDAO = new StudentsDAO(); //Создание потоков ввода-вывода, а также обертка для данных InputStream is = sock.getInputStream(); OutputStream os = sock.getOutputStream(); DataInputStream dis = new DataInputStream(is); DataOutputStream dos = new DataOutputStream(os); String line = String.valueOf(1); String stud = null; BufferedReader keyBoard = new BufferedReader(new InputStreamReader(System.in)); while(line != "ex"){ System.out.println("i wait command"); line = dis.readUTF(); System.out.println("I get command"); if (line.equals("cr")){ String finame = dis.readUTF(); System.out.println("Get FirstName"); String laname = dis.readUTF(); System.out.println("Get LastName"); String gro = dis.readUTF(); System.out.println("Get Group"); checkCopy = checkstud(finame,laname,gro); if(checkCopy){ Students stude = studDAO.createStudent(finame,laname,gro); dos.writeUTF("Student is created succesfully"); } else{ dos.writeUTF("Student is already exist"); } } if (line.equals("rd")){ List<Students> stun = studDAO.retrieveAllStudent(); String s; int i = stud.length(); dos.write(i); for (Students sud : stun){ s = sud.getFirstName(); dos.writeUTF(s); s = sud.getLastName(); dos.writeUTF(s); s = sud.getGroup(); dos.writeUTF(s); } } if (line.equals("ud")){ checkCopy = false; String ids = dis.readUTF(); int id = Integer.parseInt(ids); System.out.println("Get id"); String finame = dis.readUTF(); System.out.println("Get FirstName"); String laname = dis.readUTF(); System.out.println("Get LastName"); String gro = dis.readUTF(); System.out.println("Get Group"); studDAO.updateStudent(id, finame, laname, gro); dos.writeUTF("Student succesfully updated"); } if (line.equals("dt")){ String ids = dis.readUTF(); int id = Integer.parseInt(ids); studDAO.deleteStudent(id); dos.writeUTF("Student succesfully deleted"); } } } catch (IOException e) { System.out.println("Something Wrong with server part"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } 

Client.java

 package DataBase.Client; import DataBase.Dao.StudentsDAO; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; /** * Created by Рабочий on 17.04.2016. */ public class Client { public static void menuShow(){ System.out.println("Hello using this program you can create, look or delete students from database."); System.out.println("Please type one of the next commands"); System.out.println("1.type 'cr' to create a student "); System.out.println("2.type 'rd' to retrieve all students"); System.out.println("3.type 'ud' to update a student"); System.out.println("4.type 'dt' to delete a student"); System.out.println("0.type 'ex' to exit"); System.out.println(); } public static void main(String[] args) { int serverPort = 5555; //Серверный порт String IpAddress = "127.0.0.1"; //IP адрес StudentsDAO studDAO = new StudentsDAO(); try { InetAddress ipAdrr = InetAddress.getByName(IpAddress); //Установить интернет адрес System.out.println("Your socket is ipAddress " + ipAdrr + " server socket " + serverPort); Socket sv = new Socket(ipAdrr, serverPort); //Создание сокетов с серверным портом и интернет адресом System.out.println("Client socket is ready!"); //Создание потоков ввода-вывода, а также обертка для данных InputStream is = sv.getInputStream(); OutputStream os = sv.getOutputStream(); ObjectOutputStream odos = new ObjectOutputStream(os); DataInputStream dis = new DataInputStream(is); DataOutputStream dos = new DataOutputStream(os); //Ввод данных с клавиатуры BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); String line; String stud = null; menuShow(); line = buf.readLine(); while (!line.equals("ex")) { if (line.equals("cr")){ dos.writeUTF(line); System.out.println("Enter FirstName"); stud = buf.readLine(); dos.writeUTF(stud); System.out.println("Enter LastName"); stud = buf.readLine(); dos.writeUTF(stud); System.out.println("Enter Group"); stud = buf.readLine(); dos.writeUTF(stud); dis.readUTF(); } if (line.equals("rd")){ dos.writeUTF(line); int i = dis.read(); for (int j = 1;j<=i;j++){ String s = dis.readUTF(); System.out.print(s); String d = dis.readUTF(); System.out.print(d); String f = dis.readUTF(); System.out.println(f); } } if (line.equals("ud")) { dos.writeUTF("ud"); System.out.println("choose the 'ID' of student that you want update"); stud = buf.readLine(); dos.writeUTF(stud); System.out.println("Enter FirstName"); stud = buf.readLine(); dos.writeUTF(stud); System.out.println("Enter LastName"); stud = buf.readLine(); dos.writeUTF(stud); System.out.println("Enter Group"); stud = buf.readLine(); dos.writeUTF(stud); dis.readUTF(); } if (line.equals("dt")){ dos.writeUTF("dt"); System.out.println("choose the 'ID' of student that you want delete"); stud = buf.readLine(); dos.writeUTF(stud); dis.readUTF(); } menuShow(); line = buf.readLine(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } 

Students.java

 package DataBase.Tables; import javax.persistence.*; /** * Created by Рабочий on 20.04.2016. */ @Entity @Table(name = "students") public class Students { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "FirstName") private String FirstName; @Column(name = "LastName") private String LastName; @Column(name = "Groupstud") private String Group; public Students(String FirstName,String LastName,String Group){ this.FirstName = FirstName; this.LastName = LastName; this.Group = Group; } public Students() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return FirstName; } public void setFirstName(String firstName) { FirstName = firstName; } public String getLastName() { return LastName; } public void setLastName(String lastName) { LastName = lastName; } public String getGroup() { return Group; } public void setGroup(String group) { Group = group; } } 

hibernate.cfg.xml

 <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Teststud</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.id.new_generator_mappings">false</property> <mapping class="DataBase.Tables.Students"/> </session-factory> </hibernate-configuration> 

Server logs

 июн 03, 2016 6:18:52 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.1.0.Final} июн 03, 2016 6:18:52 PM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found июн 03, 2016 6:18:52 PM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist июн 03, 2016 6:18:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} июн 03, 2016 6:18:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) июн 03, 2016 6:18:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/Teststud] июн 03, 2016 6:18:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} июн 03, 2016 6:18:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false июн 03, 2016 6:18:53 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 20 (min=1) Fri Jun 03 18:18:53 MSK 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. июн 03, 2016 6:18:53 PM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect Waiting for a client Client is ready! июн 03, 2016 6:19:05 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) июн 03, 2016 6:19:05 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/Teststud] июн 03, 2016 6:19:05 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} июн 03, 2016 6:19:05 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false июн 03, 2016 6:19:05 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 20 (min=1) Fri Jun 03 18:19:05 MSK 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. июн 03, 2016 6:19:05 PM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect i wait command 

Client Logs

 июн 03, 2016 6:19:02 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.1.0.Final} июн 03, 2016 6:19:02 PM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found июн 03, 2016 6:19:02 PM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist июн 03, 2016 6:19:03 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} июн 03, 2016 6:19:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) июн 03, 2016 6:19:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/Teststud] июн 03, 2016 6:19:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} июн 03, 2016 6:19:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false июн 03, 2016 6:19:03 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 20 (min=1) Fri Jun 03 18:19:03 MSK 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. июн 03, 2016 6:19:04 PM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect Your socket is ipAddress /127.0.0.1 server socket 5555 Client socket is ready! Hello using this program you can create, look or delete students from database. Please type one of the next commands 1.type 'cr' to create a student 2.type 'rd' to retrieve all students 3.type 'ud' to update a student 4.type 'dt' to delete a student 0.type 'ex' to exit cr Enter FirstName dfgdfgdfg Enter LastName dfgdgdfs Enter Group asdasd 
  • well try flush() call after writeUTF - zRrr
  • No, it does not work. The server should have read the command sent. but never read it - Lukashman
  • remove in client code ObjectOutputStream odos = new ObjectOutputStream(os); it looks like it immediately writes four magic bytes to the stream when it is created, and readUTF on the server treats them as the length of the incoming string. - zRrr
  • You are a wizard! I never would have thought of it, can you tell more about these magic bytes, or throw a link to the material? - Lukashman

1 answer 1

The problem is that the ObjectOutputStream(OutputStream out) constructor immediately writes two two-byte integers STREAM_MAGIC = 0xaced and STREAM_VERSION . These numbers are needed so that the receiving ObjectInputStream immediately understand that there will be suitable data in the stream and determine the version of the protocol.

In this case, DataInputStream.readUTF takes the first two bytes as the length of the incoming string in bytes, and tries to read them all into an array. 0xACED = 44269, there is not much in the stream, so execution stops.

To solve the problem, you must either remove the creation of an ObjectOutputStream , or use ObjectOutputStream/ObjectInputStream on both sides, writeUTF/readUTF they also writeUTF/readUTF .

Links are provided at [grepcode.com], but the source code of the standard library is more convenient to look at the IDE.