Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Сокеты, ошибка 
:(
    Опции темы
Yulaw
Дата 28.2.2010, 18:55 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 15
Регистрация: 7.2.2010

Репутация: нет
Всего: нет



Код

public ConnectionInit(Connection cn,Socket client_socket,ConnectionWatcher Watvher,ServerWriter Writer)
    {
    conn = cn;
    client = client_socket;
    this.Watcher = Watcher;
    this.Writer = Writer;
    System.out.println("Connection initialization started");
    try
     {    
     BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
     out = new PrintStream(client.getOutputStream());
     //in = new DataInputStream(client.getInputStream());
     Writer.OutputStream.addElement(out);
     }    
    catch (IOException e)
      {
     try
         {
         client.close();
         }
         catch (IOException e1){};
         System.err.println("Exeption while gatting socket stream "+ e);
         return;
      } 

    System.out.println("connecteed "+String.valueOf(client.getLocalAddress()));
    this.start();
    }
    public void run()
    {
        System.out.println("ConnectionInit.run started");
        MySqlEx MySql = new MySqlEx(conn, client);
        String inline,outline;
        out.println("Welcome");
        try
            {
            while(true)
                {
                inline = in.readLine();
                System.out.println("inLine "+inline);
                if (inline == null) break;
                if (inline.equals("Disconect")){System.out.println("Client Disconnected"); break;}
                if (inline.substring(0, 1).equals("L"))
                    {
                    Lock.readLock();
                    accessLvl = MySql.getLogin(inline);
                    Lock.readUnlock();
                    if (accessLvl == 0)
                        {
                        out.println("Login fail");
                        break;
                        }
                    System.out.println("Connection with access"+accessLvl);
                    out.println("Access seccess");
                    }
                
                //Writer.outdata.push(outline);
                //synchronized(Writer){Writer.notify();}
                
                }
            }
        catch (IOException e){System.out.println("IOException in Connection.Run #1");}
        finally
            {
            try
                {
                client.close();
                in.close();
                System.out.println(" "+client.getLocalAddress()+" connection terminated");
                }
                catch (IOException e2){System.out.println("IOException in Connection.Run #2");}
                synchronized(Watcher){Watcher.notify();}
            }
    }

По какой то причине вылазит ошибка на закрытие входящего потока in.close();
Код

Exception in thread "Thread-1" java.lang.NullPointerException
    at ConnectionInit.run(Auth.java:238)

так же не хочет заходит в блок Try{} тот что после "Welcome" хотя ошибок на Catch'е нету.
Нужны свежие идеи почему так... у меня уже голова пухнет >_<. Заранее всем спасибо.
PM MAIL   Вверх
batigoal
Дата 28.2.2010, 20:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 2
Всего: 151



Yulaw, код, который ты привел, даже не скомпилируется. Приведи весь.

Телепатическим путем подозреваю, что в строке 10 не должно быть объявления, только присвоение:
Код

in = new BufferedReader(new InputStreamReader(client.getInputStream()));



--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
Yulaw
Дата 28.2.2010, 22:41 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 15
Регистрация: 7.2.2010

Репутация: нет
Всего: нет



Да Вы правы, вот полноценный код(Сильно не пинайте, это мой первый проект такого рода):
Код

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
import java.sql.Statement;
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.lang.Thread;
import java.util.Vector;
//import FIFO;
//Main Class-----------------------------------------------------------------------------------------------------------------------
public class Auth 
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        Connection DBconn = null;
        int port = 0;
        int i;
        try 
        {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        DBconn = DriverManager.getConnection("jdbc:mysql://localhost/?????","root","******"); 
        System.out.println("Connection with DB Succces!");
        }
        catch (Exception e) 
        {
            System.out.println("Connection DB fail ERROR CODE="+e.getMessage());
            System.exit(1);
        }
        if(args.length == 1)
            {
            try {port = Integer.parseInt(args[0]);}
            catch    (NumberFormatException e) {port = 0;}
            }
        new ServerInit(DBconn,port);
    }
}
//MySql Exequte Class-----------------------------------------------------------------------------------------------------------------------
class MySqlEx  // Класс отвечающий за запись и чтение с сервера
{
    private String DataSource;
    private static Connection conn;
    protected Socket client;
    protected BufferedReader in;
    protected PrintStream out;
    private Statement st;
    private ResultSet rs;
    private String[] Ps = new String[10];
    private String[] Py = new String[10];
    public MySqlEx(Connection cn,Socket client)
    {
    this.client = client;
    conn = cn;
     try
        {    
         BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
         out = new PrintStream(client.getOutputStream());
        }    
     catch (IOException e)
        {
        try
            {
             client.close();
            }
        catch (IOException e1)
            {
            System.err.println("Exeption while gatting socket stream "+ e);
            return;
            }
    } 
    }
    public void getData(String table,int id)
    {
        int i;
        String S2="";
                if(table.equals("Login"))
                {
                    Ps[0] = "Login";
                    Ps[1] = "Password";
                    Ps[2] = "Access_Level";
                    S2 = Ps[0]+","+Ps[1]+","+Ps[2];
                    i=3;//Primer
                }
                // Доделать
        try
        {            
        String SQLselect = "SELECT "+S2+" from "+table;
        st = conn.createStatement();
        rs = st.executeQuery(SQLselect);
            while(rs.next())
            {
            if (id != 0) 
                {
                }
            else
                {
                if (table.equals("Login"))
                    {
                    String a1 = rs.getString(Ps[0]);
                    String a2 = rs.getString(Ps[1]);
                    int a3 = rs.getInt(Ps[2]);
                    }
                }
            }
        }
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
            
        }
    }
    public int getLogin(String Pac) //проверка логина
    {
        // <-- Input Stream 
        // String tomnizer <--
        System.out.println("Client try input login");
        StringTokenizer T = new StringTokenizer(Pac,";");
        String Garbage = T.nextToken();
        String Login=T.nextToken();
        String Pwd=T.nextToken();
        String S1 = "Id,Login,Password,Access_Level";
        int f1 = 0;
        try
            {
            String SQLselect = "SELECT "+S1+" from logindb";
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(SQLselect);
            while(rs.next())
                {
                int id = rs.getInt("Id");
                String l1 = rs.getString("Login");
                String p1 = rs.getString("Password");
                int a1 = rs.getInt("Access_Level");
                if (l1.equals(Login) && p1.equals(Pwd))
                    { 
                    System.out.print(" Access enable - Login="+l1+" Password="+p1+" id="+id+" Accesslvl="+a1+" (");
                    f1 = a1;
                    return (int) f1;
                    }
                }    
            }
        catch (Exception e)
            {
            System.out.println(e.getMessage());
            return (int) 0;
            }
        return f1;
    }
}
//Connection with client Class----------------------------------------------------------------------------------------------------------
class ConnectionInit extends Thread     // класс отвечающий за логин
{
    static int NumberOfConnections = 0;
    protected Socket client;
    protected ConnectionWatcher Watcher;
    protected ServerWriter Writer;
    protected BufferedReader in;
    protected PrintStream out;
    private static int ID;
    private static Connection conn;
    private int accessLvl; 
    private Statement st;
    private ResultSet rs;
    RWBlock Lock;
    
    public ConnectionInit(Connection cn,Socket client_socket,ConnectionWatcher Watvher,ServerWriter Writer)
    {
    conn = cn;
    client = client_socket;
    this.Watcher = Watcher;
    this.Writer = Writer;
    System.out.println("Connection initialization started");
    try
     {    
     in = new BufferedReader(new InputStreamReader(client.getInputStream()));
     out = new PrintStream(client.getOutputStream());
     //in = new DataInputStream(client.getInputStream());
     Writer.OutputStream.addElement(out);
     }    
    catch (IOException e)
      {
     try
         {
         client.close();
         }
         catch (IOException e1){};
         System.err.println("Exeption while gatting socket stream "+ e);
         return;
      } 

    System.out.println("connecteed "+String.valueOf(client.getLocalAddress()));
    this.start();
    }
    public void run()
    {
        System.out.println("ConnectionInit.run started");
        MySqlEx MySql = new MySqlEx(conn, client);
        String inline = null,outline;
        out.println("Welcome");
        try
            {
            while(true)
                {
                System.out.println("Connection.Run while start, getting inline");
                while(inline == null)
                {
                //try{
                inline = in.readLine();
                //    }
                //catch(NullPointerException e){/*System.out.println("NullPointerException")*/;}
                }
                System.out.println("inLine "+inline);
                if (inline == null) break;
                if (inline.equals("Disconnect")){System.out.println("Client Disconnected"); break;}
                if (inline.substring(0, 1).equals("L"))
                    {
                    System.out.println("Auth start");
                    Lock.readLock();
                    accessLvl = MySql.getLogin(inline);
                    Lock.readUnlock();
                    if (accessLvl == 0)
                        {
                        out.println("Login fail");
                        System.out.println("login fail");
                        break;
                        }
                    System.out.println("Connection with access "+accessLvl);
                    out.println("Access seccess");
                    }
                
                //Writer.outdata.push(outline);
                //synchronized(Writer){Writer.notify();}
                
                }
            }
        catch (IOException e){    System.out.println("IOException in Connection.Run #1");}
        finally
            {
            try
                {
                System.out.println(" "+client.getLocalAddress()+" connection terminated");
                client.close();
                in.close();
                
                }
                catch (IOException e2){System.out.println("IOException in Connection.Run #2");}
                synchronized(Watcher){Watcher.notify();}
            }
    }
}
//Semaphore Block for Write/Read in sql  Class-----------------------------------------------------------------------------------------
class RWBlock //семафор, отвечает за целостность данных, предотвращает одновременную запись и чтение при записи.
{
    final static int EMPTY = 0;
    final static int READING = 1;
    final static int WRITING = 2;
    protected int state = EMPTY;
    protected int readCnt =0;
    public synchronized void readLock()
        {
        if (state == EMPTY)
            {
            state = READING;
            }
        else if(state == READING)
        {      }
        else if(state == WRITING)
                {
                while(state == WRITING)
                    {
                    try {wait();} 
                    catch (InterruptedException e){;}
                    }
                state = READING;
                }
        readCnt++;
        return;
        }
    public synchronized void writeLock()
        {
        if (state == EMPTY)
            {
            state = WRITING;
            }
        else
            {
            while(state != EMPTY)
                {
                try {wait();} 
                catch (InterruptedException e){;}
                }
            }
        }
    public synchronized void readUnlock()
        {
        readCnt--;
        if(readCnt == 0)
            {
            state = EMPTY;
            notify();
            }
        }
    public synchronized void writeUnlock()
        {
        state = EMPTY;
        notify();
        }
}
//Initialize main server preference Class----------------------------------------------------------------------------------------------
class ServerInit extends Thread
{
    private static Connection conn; // Переменная класса connection, которая будет хранить парамметры соединения с субд.
    public final static int DEFAULT_PORT = 6001; // Порт сервера по умолчанию.
    protected int port;
    protected ServerSocket server_port;
    protected ThreadGroup CurConnect;
    protected Vector ConList;
    protected ConnectionWatcher Watcher;
    protected ServerWriter Writer;
    protected ConsoleSpoffer CS;
    public static void fail(Exception e,String msg)
    {
        System.err.println(msg +": " +e);
        System.exit(1);
    }
    public ServerInit(Connection cn,int port)
    {
        super("Server");
        conn = cn;
        if(port == 0) port = DEFAULT_PORT;
        this.port = port;
        System.out.println("Server initialization started on port "+port);
            try    {server_port = new ServerSocket(port);}
            catch (IOException e) {fail(e,"Exception creating server socket");}
        CurConnect = new ThreadGroup("Server Connection");
        ConList = new Vector();
        Writer = new ServerWriter(this);
        Watcher = new ConnectionWatcher(this, Writer);
        CS = new ConsoleSpoffer();
        CS.start();
        this.start();
    }
    public void run()
    {
        try
            {
            System.out.println("Getting connection procces started");
            while(true)
                {
                System.out.println("Waiting for connection while started");
                Socket client_socket = server_port.accept();
                System.out.println("Connection Accepted");
                ConnectionInit c = new ConnectionInit(conn,client_socket,Watcher,Writer);
                synchronized (ConList)
                    {
                    ConList.addElement(c);
                    System.out.println("Connection list add line - "+c);
                    }


                
                }
            }
        catch  (IOException e) {fail(e,"Exception while listing for connection");}
    }
}
//Class for break old not use connections------------------------------------------------------------------------------------------------
class ConnectionWatcher extends Thread
{
    protected ServerInit server;
    protected ServerWriter writer;
    protected ConnectionWatcher(ServerInit s,ServerWriter writer)
    {
        super(s.CurConnect, "Connection Watcher");
        server = s;
        this.writer = writer;
        System.out.println("Connection watcher started");
        this.start();
    }
    public synchronized void run()
    {
        System.out.println("Process connection watcher started");
    while(true)
        {//20 sec wait
        try    {this.wait(10000);}
        catch (InterruptedException e){System.out.println("Caught an Interrupted Exception");}
        synchronized(server.ConList)
            {
            for (int i =0;i<server.ConList.size();i++)
                {
                ConnectionInit c;
                c = (ConnectionInit) server.ConList.elementAt(i);
                if (!c.isAlive())
                    {
                    System.out.println("Connection list Delete line "+server.ConList.elementAt(i));
                    server.ConList.removeElementAt(i);
                    writer.OutputStream.removeElementAt(i);//Writer
                    
                    i--;
                    }
                }
            }
        }
    }
}
//Main ItPut to Client Class, he doing all input operations---------------------------------------------------------------------------------
class ServerWriter extends Thread
{
    ServerInit server;
    public Vector OutputStream;
    public FIFO outdata;
    private String outputline;
    public int Target;
    
    public ServerWriter(ServerInit s)
    { super("Server Writer");
      server = s;
      OutputStream = new Vector();
      outdata = new FIFO();
      System.out.println("server writer started");
      this.start();
    }
    public synchronized void run()
    {
        System.out.println("Server writer process started");
        
    while(true)
        {
        try{this.wait();}
        catch(InterruptedException e){System.out.println("Caught an Interrupted Exception");}
        outputline =(String) outdata.pop();
        synchronized(server.ConList)
        {
                PrintStream out;
                out = (PrintStream)OutputStream.elementAt(Target);
                out.println(outputline);
        }
        }
    }
}
class FIFO extends Vector
{
    public String pop()
    {
    String s="";
    try {
    s= (String) firstElement();
    }
    catch (NoSuchElementException e)
        {System.out.println("FIFO EMPTY!");
        s="";
        }
    try {
        removeElement(s);
        }
    catch (ArrayIndexOutOfBoundsException e)
    {
        System.out.println("FIFO EMPTY!");
    }
    return s;
    }
    public void push(String s)
    {
    addElement(s);
    }
    public boolean empty()
    {
    return isEmpty();
    }
}
class ConsoleSpoffer extends Thread
{
    public String Command;
    public boolean check;
    protected BufferedReader inS; 
    
    public synchronized void run()
    {
        inS = new BufferedReader(new InputStreamReader(System.in));
        while(true)
        {
        try {
            Command =(String) inS.readLine();
            check = true;
            System.out.println("Write Command Success");
        } catch (IOException e) {
            System.out.println("IOException ConsoleSpoffer");
        }
        System.out.println("--->1");
        if (this.check == true)
        {System.out.println("--->2");
            if(this.Command.equals("Exit"))
            {
            System.out.println("Program shutdown");
            System.exit(0);
            check = false;
            }
            
        }    
        }
    }
}

 Классы FIFO и ServerWriter пока нигде не используются, метод MySqlEx.getData не доделан.
 Да действительно BufferedReader был лишним.
 Появились еще проблемы:
 1) в 224 строке почему то не выполняется мотод MySql.getLogin()
 2) Использую в качестве клиента Visual С++ в котором пока что довольно плохо шарю,
     по какой-то причине джава не начинает обработку входящей строки(inline = in.readLine(); на 213 строке) пока не разорвется связь со стороны клиента

PM MAIL   Вверх
batigoal
Дата 1.3.2010, 11:07 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Нелетучий Мыш
****


Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 2
Всего: 151



Цитата(Yulaw @  28.2.2010,  23:41 Найти цитируемый пост)
по какой-то причине джава не начинает обработку входящей строки(inline = in.readLine(); на 213 строке) пока не разорвется связь со стороны клиента

Скорее всего, у сервера и клиента здесь разные понятия о том, что есть end of line. Попробуй читать не через readLine(), а побайтово, и посмотри, что выведется.

Цитата(Yulaw @  28.2.2010,  23:41 Найти цитируемый пост)
 1) в 224 строке почему то не выполняется мотод MySql.getLogin()

С какой ошибкой?


--------------------
"Чтобы правильно задать вопрос, нужно знать большую часть ответа" (Р. Шекли)
ЖоржЖЖ
PM WWW   Вверх
Yulaw
Дата 1.3.2010, 16:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 15
Регистрация: 7.2.2010

Репутация: нет
Всего: нет



c MySql.getLogin() похоже все просто, поток ConnectionWatcher отвечающий за прерывания не активных соединений прерывает раньше чем успевает дойти до этого метода. А что касается ReadLine исправил, добавил в пакет со стороны клиента символ перевода каретки, но тут же новые проблемы теперь опять  MySql.getLogin() как только до него доходит перекидывает на finally c ошибкой Exception in thread "Thread-2" java.lang.NullPointerException
    at ConnectionInit.run(Auth.java:252)(ссылка на synchronized(Watcher){Watcher.notify();}), метод MySql.getLogin() не запускался, это может быть из-за методов Lock.readLock Lock.readUnlock(отвечают за предотвращение одновременного чтения и записи) класса RWBlock? Или это ошибка  MySql.getLogin()?

Upd: Простите, я не заметил что не инициализировал новый экземпляр класса  RWBLock, но ошибка Exception in thread "Thread-2" java.lang.NullPointerException
    at ConnectionInit.run(Auth.java:252)(ссылка на synchronized(Watcher){Watcher.notify();}) так и ни куда не делась, хоть она не на что не влияет, хотелось бы знать ее причину

П.С. Как я уже говорил, что в Visual C++ плохо разбираюсь, если не затруднит, может кто нибудь поделится исходником MDI приложения в котором были бы готовые методы для соединения, отправки и приема данных, которые можно было бы вызвать из любого дочернего диалогового окна, но это только конечно если не затруднит. В любом случае буду очень благодарен!     
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Работа с сетью | Следующая тема »


 




[ Время генерации скрипта: 0.0516 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.