Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by BUHARIN on 04.09.2016.
- */
- import java.io.*;
- import java.net.*;
- import java.sql.*;
- import java.util.ArrayList;
- class ServeOneJabber extends Thread {
- private Socket socket;
- private BufferedReader in;
- private PrintWriter out;
- private Connection conn;
- private Statement stat;
- ResultSet rs;
- public ObjectOutputStream oos;
- public ServeOneJabber(Socket s) throws IOException, ClassNotFoundException, SQLException {
- Class.forName("org.postgresql.Driver");
- conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "1");
- stat = conn.createStatement();
- stat.execute("SELECT * FROM \"public\".\"KBK\";");
- rs = stat.executeQuery("SELECT * FROM \"public\".\"KBK\";");
- socket = s;
- in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- oos = new ObjectOutputStream(socket.getOutputStream());
- // Включаем автоматическое выталкивание:
- out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
- // Если любой из вышеприведенных вызовов приведет к
- // возникновению исключения, то вызывающий отвечает за
- // закрытие сокета. В противном случае, нить
- // закроет его.
- start(); // вызываем run()
- }
- public void run() {
- try {
- while (true) {
- String str = in.readLine();
- System.out.println(str);
- if (str.equals("END"))
- break;
- ArrayList<KBK> beans = new ArrayList<KBK>();
- try {
- while (rs.next()) {
- try {
- beans.add(new KBK(rs.getString("Key") ,rs.getString("Kod") ,rs.getString("Name") ));
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- oos.writeObject(beans);
- oos.flush();
- }
- System.out.println("closing...");
- }
- catch (IOException e) {
- System.err.println("IO Exception");
- }
- finally {
- try {
- socket.close();
- }
- catch (IOException e) {
- System.err.println("Socket not closed");
- }
- }
- }
- }
- public class MultiServer {
- static final int PORT = 8080;
- public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
- ServerSocket s = new ServerSocket(PORT);
- System.out.println("Server Started");
- try {
- while (true) {
- // Блокируется до возникновения нового соединения:
- Socket socket = s.accept();
- try {
- new ServeOneJabber(socket);
- }
- catch (IOException e) {
- // Если завершится неудачей, закрывается сокет,
- // в противном случае, нить закроет его:
- socket.close();
- }
- }
- }
- finally {
- s.close();
- }
- }
- } // /:~
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement