Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package chat.server;
- import chat.network.TCPConnection;
- import chat.network.TCPConnectionListener;
- import com.sun.security.ntlm.Server;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.util.ArrayList;
- public class ChatServer implements TCPConnectionListener {
- public static void main(String[] args){
- new ChatServer();
- }
- private final ArrayList<TCPConnection> connections = new ArrayList<>();
- private ChatServer(){
- System.out.println("Server ruuning...");
- try(ServerSocket serverSocket = new ServerSocket(8189)){
- while(true){
- try{
- new TCPConnection(this, serverSocket.accept());
- }catch(IOException e){
- System.out.println("TCPConnection exception: " + e);
- }
- }
- }catch (IOException e){
- throw new RuntimeException(e);
- }
- }
- @Override
- public synchronized void onCOnnectionReady(TCPConnection tcpConnection) {
- connections.add(tcpConnection);
- }
- @Override
- public synchronized void onRecieveString(TCPConnection tcpConnection, String value) {
- sendToAllConnections(value);
- }
- @Override
- public synchronized void onDisconnect(TCPConnection tcpConnection) {
- connections.remove(tcpConnection);
- sendToAllConnections("Client disconnect: " + tcpConnection);
- }
- @Override
- public synchronized void onException(TCPConnection tcpConnection, Exception e) {
- System.out.println("TCPConnection exception: " + e);
- }
- private void sendToAllConnections(String value){
- System.out.println(value);
- final int cnt = connections.size();
- for(int i = 0; i < cnt; i++) connections.get(i).sendString(value);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement