Server

Server main file
mail@pastecode.io avatar
unknown
java
4 years ago
1.5 kB
1
Indexable
Never
package server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {

	private ServerSocket serverSocket;
	private Socket socket;
	private List<ServerThread> connections;
	private List<String> clients;
	private List<String> messages;
	
	public Server() throws Exception {
		
		connections = new ArrayList<>();
		serverSocket = new ServerSocket(4444);
		clients = new ArrayList<>();
		messages = new ArrayList<>();
		
		System.out.println("Server started!");
		
		while (true) {
			
			socket = serverSocket.accept();	
			
			ServerThread serverThread = new ServerThread(socket, this);
			Thread thread = new Thread(serverThread);
			connections.add(serverThread);
			
			thread.start();
		}
	}
	
	public void sendToAllClients(String message, ServerThread serverThread) {
		for (ServerThread s : connections) {
			if (s == serverThread) {
				continue;
			} else {
				s.sendMessage(message);
			}
		}
	}
	
	
	
	public void setClientName(String name) {
		clients.add(name);
	}
	
	
	public boolean getNane(String name) {
		return clients.contains(name);
	}
	
	public void setMessages(String message) {
		messages.add(message);
	}
	
	public List<String> getMessages() {
		return messages;
	}
	
	public static void main(String[] args) {
		try {
			new Server();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}