Advertisement
Guest User

ChatServer

a guest
Jul 17th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. package chat.server;
  2.  
  3. import chat.network.TCPConnection;
  4. import chat.network.TCPConnectionListener;
  5. import com.sun.security.ntlm.Server;
  6.  
  7. import java.io.IOException;
  8. import java.net.ServerSocket;
  9. import java.util.ArrayList;
  10.  
  11. public class ChatServer implements TCPConnectionListener {
  12. public static void main(String[] args){
  13. new ChatServer();
  14. }
  15.  
  16. private final ArrayList<TCPConnection> connections = new ArrayList<>();
  17.  
  18.  
  19. private ChatServer(){
  20. System.out.println("Server ruuning...");
  21. try(ServerSocket serverSocket = new ServerSocket(8189)){
  22. while(true){
  23. try{
  24. new TCPConnection(this, serverSocket.accept());
  25. }catch(IOException e){
  26. System.out.println("TCPConnection exception: " + e);
  27. }
  28. }
  29. }catch (IOException e){
  30. throw new RuntimeException(e);
  31. }
  32. }
  33.  
  34. @Override
  35. public synchronized void onCOnnectionReady(TCPConnection tcpConnection) {
  36. connections.add(tcpConnection);
  37. }
  38.  
  39. @Override
  40. public synchronized void onRecieveString(TCPConnection tcpConnection, String value) {
  41. sendToAllConnections(value);
  42. }
  43.  
  44. @Override
  45. public synchronized void onDisconnect(TCPConnection tcpConnection) {
  46. connections.remove(tcpConnection);
  47. sendToAllConnections("Client disconnect: " + tcpConnection);
  48. }
  49.  
  50. @Override
  51. public synchronized void onException(TCPConnection tcpConnection, Exception e) {
  52. System.out.println("TCPConnection exception: " + e);
  53. }
  54.  
  55. private void sendToAllConnections(String value){
  56. System.out.println(value);
  57. final int cnt = connections.size();
  58. for(int i = 0; i < cnt; i++) connections.get(i).sendString(value);
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement