ServerThread class

mail@pastecode.io avatar
unknown
java
4 years ago
1.3 kB
1
Indexable
Never
package Server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

public class ServerThread implements Runnable {

	private Socket socket;
	private Server server;
	private DataInputStream input;
	private DataOutputStream output;
	
	public ServerThread(Socket socket, Server server) throws Exception {
		this.socket = socket;
		this.server = server;
		this.input = new DataInputStream(socket.getInputStream());
		this.output = new DataOutputStream(socket.getOutputStream());
	}
	
	@Override
	public void run() {
		
		int clientNumber = server.getClientNumber();
		System.out.println("Client " + clientNumber + " connected!");
		
		try {
			
			while (true) {
				
				String message = input.readUTF();
				if (message.equals("/exit")) {
					System.out.println("Client " +clientNumber + " disconnected!");
					socket.close();
					output.close();
					input.close();
					break;
					
				} else {
					
					System.out.println("Client " + clientNumber + " send: " + message);
					
					System.out.println("Sent to client " + clientNumber + ": Count is " + server.countWords(message));
					output.writeUTF("Count is " + server.countWords(message));

				}				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}