×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Andro Max
Added: Nov 1, 2018 1:19 PM
Views: 3488
Tags: no tags
  1. package serverchat;
  2.  
  3. import java.awt.Container;
  4. import java.awt.FlowLayout;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.io.IOException;
  8. import java.net.InetAddress;
  9. import java.net.InetSocketAddress;
  10. import java.net.ServerSocket;
  11. import java.net.SocketAddress;
  12. import java.nio.ByteBuffer;
  13. import java.nio.channels.SelectionKey;
  14. import java.nio.channels.Selector;
  15. import java.nio.channels.ServerSocketChannel;
  16. import java.nio.channels.SocketChannel;
  17. import java.nio.charset.Charset;
  18. import java.nio.charset.CharsetDecoder;
  19. import java.nio.charset.CoderResult;
  20. import java.util.Iterator;
  21. import java.util.LinkedList;
  22. import java.util.Set;
  23. import javax.swing.JButton;
  24. import javax.swing.JFrame;
  25. import javax.swing.JLabel;
  26. import javax.swing.JScrollPane;
  27. import javax.swing.JTextArea;
  28.  
  29.  
  30. public class myFrame extends JFrame{
  31.    
  32.     /** Creates a new instance of myFrame */
  33.     private JTextArea ChatBox=new JTextArea(10,45);
  34.     private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
  35.             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
  36.     private JTextArea UserText = new JTextArea(5,40);
  37.     private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
  38.             JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  39.     private JButton Send = new JButton("Send");
  40.     private JButton Start = new JButton("Start Server!");
  41.     private server ChatServer;
  42.     private InetAddress ServerAddress ;
  43.    
  44.     public myFrame() {
  45.         setTitle("Server");
  46.         setSize(560,400);
  47.         Container cp=getContentPane();
  48.         cp.setLayout(new FlowLayout());
  49.         cp.add(new JLabel("Server History"));
  50.         cp.add(myChatHistory);
  51.         cp.add(new JLabel("Chat Box : "));
  52.         cp.add(myUserHistory);
  53.         cp.add(Send);
  54.         cp.add(Start);
  55.        
  56.        
  57.        
  58.         Start.addActionListener(new ActionListener() {
  59.             public void actionPerformed(ActionEvent e) {
  60.                
  61.                 ChatServer=new server();
  62.                 ChatServer.start();
  63.                
  64.             }
  65.         });
  66.         Send.addActionListener(new ActionListener() {
  67.             public void actionPerformed(ActionEvent e) {
  68.                 ChatServer.SendMassage(ServerAddress.getHostName()+" < Server > "+UserText.getText());
  69.             }
  70.         });
  71.        
  72.        
  73.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  74.         setVisible(true);
  75.        
  76.        
  77.     }
  78.    
  79.     /**
  80.      * @param args the command line arguments
  81.      */
  82.     public static void main(String[] args) {
  83.         // TODO code application logic here
  84.         new myFrame();
  85.     }
  86.    
  87.    
  88.     public class server extends Thread {
  89.         private static final int PORT=9999;
  90.         private LinkedList Clients;
  91.         private ByteBuffer ReadBuffer;
  92.         private ByteBuffer WriteBuffer;
  93.         public  ServerSocketChannel SSChan;
  94.         private Selector ReaderSelector;
  95.         private CharsetDecoder asciiDecoder;
  96.        
  97.        
  98.         public server() {
  99.             Clients=new LinkedList();
  100.             ReadBuffer=ByteBuffer.allocateDirect(300);
  101.             WriteBuffer=ByteBuffer.allocateDirect(300);
  102.             asciiDecoder = Charset.forName( "US-ASCII").newDecoder();
  103.         }
  104.        
  105.         public void InitServer() {
  106.             try {
  107.                 SSChan=ServerSocketChannel.open();
  108.                 SSChan.configureBlocking(false);
  109.                 ServerAddress=InetAddress.getLocalHost();
  110.                 System.out.println(ServerAddress.toString());
  111.                
  112.                 SSChan.socket().bind(new InetSocketAddress(ServerAddress,PORT));
  113.                
  114.                 ReaderSelector=Selector.open();
  115.                 ChatBox.setText(ServerAddress.getHostName()+"<Server> Started. \n");
  116.             } catch (IOException ex) {
  117.                 ex.printStackTrace();
  118.             }
  119.         }
  120.         public void run() {
  121.             InitServer();
  122.            
  123.             while(true) {
  124.                 acceptNewConnection();
  125.                
  126.                 ReadMassage();
  127.                 try {
  128.                     Thread.sleep(100);
  129.                 } catch (InterruptedException ex) {
  130.                     ex.printStackTrace();
  131.                 }
  132.                
  133.                
  134.             }
  135.         }
  136.        
  137.         public void acceptNewConnection() {
  138.             SocketChannel newClient;
  139.             try {
  140.                
  141.                 while ((newClient = SSChan.accept()) != null) {
  142.                     ChatServer.addClient(newClient);
  143.                    
  144.                     sendBroadcastMessage(newClient,"Login from: " +newClient.socket().getInetAddress());
  145.                    
  146.                     SendMassage(newClient,ServerAddress.getHostName()+"<server> welcome you !\n Note :To exit" +
  147.                             " from server write 'quit' .\n");
  148.                 }
  149.                
  150.             } catch (IOException e) {
  151.                 e.printStackTrace();
  152.             }
  153.            
  154.         }
  155.        
  156.         public void addClient(SocketChannel newClient) {
  157.             Clients.add(newClient);
  158.             try {
  159.                 newClient.configureBlocking(false);
  160.                 newClient.register(ReaderSelector,SelectionKey.OP_READ,new StringBuffer());
  161.                
  162.             } catch (IOException ex) {
  163.                 ex.printStackTrace();
  164.             }
  165.         }
  166.        
  167.         public void SendMassage(SocketChannel client ,String messg) {
  168.             prepareBuffer(messg);
  169.             channelWrite(client);
  170.         }
  171.         public void SendMassage(String massg) {
  172.             if(Clients.size()>0) {
  173.                 for(int i=0;i<Clients.size();i++) {
  174.                     SocketChannel client=(SocketChannel)Clients.get(i);
  175.                     SendMassage(client,massg);
  176.                 }
  177.             }
  178.         }
  179.        
  180.        
  181.         public void prepareBuffer(String massg) {
  182.             WriteBuffer.clear();
  183.             WriteBuffer.put(massg.getBytes());
  184.             WriteBuffer.putChar('\n');
  185.             WriteBuffer.flip();
  186.         }
  187.        
  188.         public void channelWrite(SocketChannel client) {
  189.             long num=0;
  190.             long len=WriteBuffer.remaining();
  191.             while(num!=len) {
  192.                 try {
  193.                     num+=client.write(WriteBuffer);
  194.                    
  195.                     Thread.sleep(5);
  196.                 } catch (IOException ex) {
  197.                     ex.printStackTrace();
  198.                 } catch(InterruptedException ex) {
  199.                    
  200.                 }
  201.             }
  202.             WriteBuffer.rewind();
  203.         }
  204.        
  205.         public void sendBroadcastMessage(SocketChannel client,String mesg) {
  206.             prepareBuffer(mesg);
  207.             Iterator i = Clients.iterator();
  208.             while (i.hasNext()) {
  209.                 SocketChannel channel = (SocketChannel)i.next();
  210.                 if (channel != client) {
  211.                     channelWrite(channel);
  212.                 }
  213.             }
  214.         }
  215.         public void ReadMassage() {
  216.             try {
  217.                
  218.                 ReaderSelector.selectNow();
  219.                 Set readkeys=ReaderSelector.selectedKeys();
  220.                 Iterator iter=readkeys.iterator();
  221.                 while(iter.hasNext()) {
  222.                     SelectionKey key=(SelectionKey) iter.next();
  223.                     iter.remove();
  224.                    
  225.                     SocketChannel client=(SocketChannel)key.channel();
  226.                     ReadBuffer.clear();
  227.                    
  228.                     long num=client.read(ReadBuffer);
  229.                    
  230.                     if(num==-1) {
  231.                         client.close();
  232.                         Clients.remove(client);
  233.                         sendBroadcastMessage(client,"logout: " +
  234.                                 client.socket().getInetAddress());
  235.                        
  236.                     } else {
  237.                        
  238.                         StringBuffer str=(StringBuffer)key.attachment();
  239.                         ReadBuffer.flip();
  240.                         String data= asciiDecoder.decode(ReadBuffer).toString();
  241.                         ReadBuffer.clear();
  242.                        
  243.                         str.append(data);
  244.                        
  245.                         String line = str.toString();
  246.                         if ((line.indexOf("\n") != -1) || (line.indexOf("\r") != -1)) {
  247.                             line = line.trim();
  248.                             System.out.println(line);
  249.                            
  250.                             if (line.endsWith("quit")) {
  251.                                 client.close();
  252.                                
  253.                                 Clients.remove(client);
  254.                                
  255.                                 ChatBox.append("Logout: " + client.socket().getInetAddress());
  256.                                
  257.                                 sendBroadcastMessage(client,"Logout: "
  258.                                         + client.socket().getInetAddress());
  259.                                 ChatBox.append(""+'\n');
  260.                             } else {
  261.                                 ChatBox.append(client.socket().getInetAddress() + ": " + line);
  262.                                
  263.                                 sendBroadcastMessage(client,client.socket().getInetAddress()
  264.                                 + ": " + line);
  265.                                
  266.                                 ChatBox.append(""+'\n');
  267.                                
  268.                                 str.delete(0,str.length());
  269.                             }
  270.                         }
  271.                     }
  272.                 }
  273.                
  274.             } catch (IOException ex) {
  275.                 ex.printStackTrace();
  276.             }
  277.         }
  278.     }
  279.    
  280. }