ObjectInputStream.readObject, кажется, застрял в многопоточном сервере - PullRequest
0 голосов
/ 01 мая 2018

Я пытаюсь отправить пешеходный объект на сервер и сервер, чтобы вернуть список водителей автомобилей в объекте сообщения. Но когда я пытаюсь отправить сервер, кажется, застрял в функции readObject, и клиент не в состоянии инициализировать выходные данные объекта и входные потоки. Вот мой код сервера:

package eece350;
import java.util.List;
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;
/**
 *
 * @author user
 */
public class SkillsServer {
    private ServerSocket serverSocket;
    private void acceptConnections() {
    try {
            int port = 7171;
            serverSocket = new ServerSocket(port);
        } 
    catch (IOException e) 
        {
            System.err.println("ServerSocket instantiation failure");
            e.printStackTrace();
            System.exit(0);
    }
// Entering the infinite loop
    while (true) {
                        try {
                            // wait for a TCP handshake initialization (arrival of a "SYN"
                            // packet)
                Socket newConnection = serverSocket.accept();
                System.out.println("accepted connection");
                // Now, pass the connection socket created above to a thread and
                // run it in it
                // First create the thread and pass the connection socket to it
                // This is a non-blocking function: constructor of the class
                // ServerThread
                ServerThread st = new ServerThread(newConnection);
                // Then, start the thread, and go back to waiting for another
                // TCP connection
                // This also is not blocking
                new Thread(st).start();
            } 
                        catch (IOException ioe)
                        {
                            System.err.println("server accept failed");
            }
        }
    }
    public static void main(String[] args) throws NullPointerException, ClassNotFoundException, FileNotFoundException, SQLException 
    {
        SkillsServer server = null;
        server= new SkillsServer();
        // call this function, which will start it all...
        server.acceptConnections();
    }
    // Internal class
    class ServerThread implements Runnable
    {
        private Socket socket;
                private ObjectOutputStream dataout;
        private ObjectInputStream datain;
                //private DataOutputStream outToClient;
        ServerThread(Socket socket) 
                {
            // Inside the constructor: store the passed object in the data
            // member
            this.socket = socket;
        }
  private List<CarDriver> getAllCarDriversWithCapacity() throws SQLException
  {
      String userName = "Mahdi";
        String password = "admin";
        String url ="jdbc:sqlserver://localhost:1433"+";databaseName=Project350;Integrated Security=True";
        try 
        {   
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } 
        catch (ClassNotFoundException ex) 
        {
            System.out.println("Cannot connect to database");
        }
        Connection conn = DriverManager.getConnection(url,userName,password);
        // TODO code application logic here
        Statement stmt = conn.createStatement();
        String query= "select * from CarDriver";
        ResultSet rs =stmt.executeQuery(query);
        CarDriver Car = new CarDriver();
        List<CarDriver> ListofDrivers = new ArrayList<>();
        while(rs.next())
        {
            if(rs.getInt(12)>0)
            {
                Car.setDid(rs.getInt(0));
                Car.setName(rs.getString(1));
                Coordinates C = new Coordinates(rs.getDouble(2),rs.getDouble(3));
                Car.setLocation(C);
                C.setCoordinates(rs.getDouble(4),rs.getDouble(5));
                Car.setDestination(C);
                Car.setNumofPassengers(rs.getInt(6));
                Car.setChargingPerKilometer(rs.getDouble(7));
                Regulations r = new Regulations(rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11));
                Car.setRegulations(r);
                Car.setCarCapacity(rs.getInt(12));
                ListofDrivers.add(Car);
            }
        }
        rs.close();
        conn.close();
        return ListofDrivers;
  }
  private void InsertCarDriver(CarDriver cardriver) throws SQLException
    {
        String name=cardriver.getName();
        Coordinates Location=cardriver.getLocation();
        int did=cardriver.getDid();
        Coordinates Destination=cardriver.getDestination();
        int numberofPassengers=cardriver.getNumofPassengers();
        int CarCapacity=cardriver.getCarCapacity();
        Double charging=cardriver.getChargingPerKilometer();
        Regulations regulations=cardriver.getRegulations();
        String pets = regulations.pets;
        String kids = regulations.kids;
        String quietride = regulations.quietRide;
        String smoking = regulations.smoking;
        Double XLoc = Location.coordinateX;
        Double YLoc = Location.coordinateY;
        Double XDes = Destination.coordinateX;
        Double YDes = Destination.coordinateY;
        String userName = "Mahdi";
        String password = "admin";
        String url ="jdbc:sqlserver://localhost:1433"+";databaseName=Project350;Integrated Security=True";
        try 
        {   
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } 
        catch (ClassNotFoundException ex) 
        {
            System.out.println("Cannot connect to database");
        }
        Connection conn = DriverManager.getConnection(url,userName,password);
        // TODO code application logic here
        Statement stmt = conn.createStatement();
        String query = "Insert into CarDriver values("+did+",'"+name+"',"+XLoc+","+YLoc+","+XDes+","+YDes+","+numberofPassengers+","+charging+",'"+smoking+"','"+pets+"','"+kids+"','"+quietride+"',"+CarCapacity+")";
        stmt.execute(query);
        conn.close();
    }
        public void run() 
        {
        try 
        {
    // Input and output streams, obtained from the member socket
    // object
             //outToClient = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()))
             dataout = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
             datain = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
        } 
        catch (IOException e) 
        {
            System.out.println("Can't Initialize Streams");
        }
            String name="";
            Coordinates location;
            Coordinates Destination;
            int numberofPassenger;
            double chargingPerKilometer;
            int carCapacity,did;
            Regulations regulations;
            boolean connectionActive = true;
            String reply="";
            while (connectionActive) 
            {

                try 
                {
                    Object object;
                    object = datain.readObject();
                    if(object instanceof CarDriver)
                    {
                        /*String url ="jdbc:sqlserver://localhost:1433"+";databaseName=EECE350Project;Integrated Security=True";
                        String userName = "Mahdi";
                        String password = "admin";
                        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                        Connection conn = DriverManager.getConnection(url,userName,password);
                        Statement stmt = conn.createStatement();*/
                        CarDriver CarDriver1 = (CarDriver)object;
                        name=CarDriver1.getName();
                        location=CarDriver1.getLocation();
                        Destination=CarDriver1.getDestination();
                        numberofPassenger=CarDriver1.getNumofPassengers();
                        chargingPerKilometer=CarDriver1.getChargingPerKilometer();
                        carCapacity = CarDriver1.getCarCapacity();
                        regulations = CarDriver1.getRegulations();
                        did=CarDriver1.getDid();
                        reply = "I recieved your connection "+name;
                        this.InsertCarDriver(CarDriver1);
                        //outToClient.write(reply.getBytes(),0,reply.length());
                        //outToClient.write("\n".getBytes(),0,1);
                        //outToClient.flush();
                            try
                            {
                                System.out.println("Closing Socket");
                                datain.close();
                                //outToClient.close();
                                dataout.close();
                                socket.close();
                            }
                            catch(IOException ioe)
                            {
                                System.out.println("Unable to Close Socket");          
                            }
                    } 
                    else 
                    {
                        System.out.println("Hello");
                        Regulations Pedregulations;
                        int pid=0;
                        Coordinates Pedlocation;
                        Coordinates PedDestination;
                        Pedestrian Pedestrian1 = (Pedestrian)object;
                        pid = Pedestrian1.pid;
                        Pedlocation = Pedestrian1.currentLocation;
                        PedDestination = Pedestrian1.Destination;
                        List <CarDriver> ListofCars = this.getAllCarDriversWithCapacity();
                        String mes = "";
                        Message message = new Message();
                        message.setMessage(ListofCars, mes);
                        reply= "I recieved your connection"+pid;
                        System.out.println(pid);
                        dataout.writeObject(message);
                        dataout.flush();
                    //outToClient.write(reply.getBytes(),0,reply.length());
                        //outToClient.write("\n".getBytes(),0,1);
                        //outToClient.flush();
                        //outToClient.writeBytes(reply);
                            try
                            {
                                System.out.println("Closing Socket");
                                datain.close();
                                //outToClient.close();
                                dataout.close();
                                socket.close();
                            }
                            catch(IOException ioe)
                            {
                                System.out.println("Unable to Close Socket");          
                            }
                        }
                }            
                catch (IOException ex) 
                {
                   System.out.println("No Object Recieved"); 
                } 
                catch (ClassNotFoundException ex) 
                { 
                    System.out.println("Class");
                } 
                catch (SQLException ex) 
                { 
                Logger.getLogger(SkillsServer.class.getName()).log(Level.SEVERE, null, ex);
                } 
                //catch (SQLException ex) 
                //{
                    //return;
                //} 
            }
                try 
                {
        System.out.println("closing socket");
        datain.close();
        dataout.close();
        socket.close();
                } 
                    catch (IOException e) 
                        {
                            System.out.print('.');
                        }
                }
            }
        }

вот мой код клиента:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package eece350;
import java.io.Serializable;
import java.io.*; 
import java.net.*;
import java.util.ArrayList;
import java.util.List;
/**
 *
 * @author user
 */
// double hey = Double.parseDouble(string);
public class Pedestrian implements Serializable 
{
    public int pid=0;
    public Coordinates currentLocation;
    public Coordinates Destination;
    public Regulations preferences;
    public Pedestrian()
    {
        this.pid=0;
        this.Destination=null;
        this.currentLocation=null;
        this.preferences=null;
    }
    public Pedestrian(Coordinates currentLocation,Coordinates Destination,int pid,Regulations preferences) throws IOException, ClassNotFoundException
    {
        this.pid=pid;
        this.Destination=Destination;
        this.currentLocation=currentLocation;
        this.preferences=preferences;
        Socket clientSocket = new Socket("localhost", 7171); 
        ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
        ObjectInputStream inFromServer = new ObjectInputStream(clientSocket.getInputStream()); 
        //BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        //String modifiedSentence="";
        System.out.println("heyo");
        outToServer.writeObject(this);
        Object object;
        object = inFromServer.readObject();
        if(object instanceof Message)
        {
            Message m = (Message)object;
            if(m.CarDrivers!=null)
            {
                for(int i =0;i<m.CarDrivers.size();i++)
                {
                    System.out.print(m.CarDrivers.get(i).getName());
                }
            }
        } 
        else 
        {
            System.out.print("Not a message");
        }
        //modifiedSentence = inFromServer.readLine();
        //System.out.println("FROM SERVER: " + modifiedSentence);
        outToServer.close();
        inFromServer.close();
        outToServer.flush();
        clientSocket.close();
    }
    public static void main(String argv[]) throws Exception
    {

    }
}

Пожалуйста, кто-нибудь может мне помочь?

...