Главная страница Случайная страница КАТЕГОРИИ: АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника |
NetServer.java
/* * 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 jChatServer;
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane;
/** * * @author VasVas */ public class netServer extends Thread{ private int PORT = 80; private volatile ServerSocket s = null; private ArrayList< Client> clients= new ArrayList< > (); private frmServer frm; public netServer(int PORT, frmServer a){ this.PORT=PORT; Resender.createNew(clients); frm=a; } public void startServer(){ start(); } public ServerSocket getSS(){ return s; } public void run(){ int id=1; try { s = new ServerSocket(PORT); System.out.println(" Server Started"); int flag=1; Socket socket = null; while(flag==1) { // Блокуєтся до винекнення нового зєднання:
try{ socket = s.accept(); clients.add(new Client(socket, id)); id++; }catch(SocketException ex){ if(Thread.currentThread().isInterrupted()){ //отключити клыэнтыв stopClients(); flag=0; } // stopClients(); break; } } }catch (IOException ex) { System.out.println(ex); frm.resetServerStart(ex.toString()); } finally { try { if(s! =null)s.close(); } catch (IOException ex) { Logger.getLogger(netServer.class.getName()).log(Level.SEVERE, null, ex); } } } private void stopClients(){ for(Client c: clients){ c.sendMsg(" EXIT"); } for(Client c: clients){ c.cloosing(); c.stop(); } clients.clear(); } public void stopServer(){ try { s.close(); //stopClients(); } catch (IOException ex) { Logger.getLogger(netServer.class.getName()).log(Level.SEVERE, null, ex); } } }
class Client extends Thread{ private Socket socket; private BufferedReader in; private PrintWriter out; private int clientID; Client(Socket s, int clientID){ this.clientID=clientID; try { socket=s; in =new BufferedReader( new InputStreamReader( socket.getInputStream())); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); start(); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } public void run(){ try { String str=" "; while (true) { str = in.readLine(); if (str.equals(" END")) break; Resender.getObj().sendAll(str); } System.out.println(" Закриття клієнта..." +clientID); cloosing(); } catch(IOException e) { System.err.println(" IO Exception"); } finally { try { in.close(); out.close(); socket.close(); } catch(IOException e) { System.err.println(" Socket не закритий"); } } }
public void sendMsg(String msg){ out.println(msg); }
public void cloosing(){ try { in.close(); out.close(); socket.close(); } catch(IOException e) { System.err.println(" Socket не закритий"); } } }
class Resender{ private ArrayList< Client> clients; private static Resender item=null;
public static Resender getObj(){ return item; } public static void createNew(ArrayList< Client> group){ if(item==null){item = new Resender(group); } else{item.clients=group; } } private Resender(ArrayList< Client> group){ clients=group; } public void sendAll(String msg){ for(Client c: clients){ c.sendMsg(msg); } } }
|