package kr.co.swh.lecture.opensource.project.drawing; 

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * <pre>
 * kr.co.swh.lecture.network.chat 
 * ServerThread.java
 *
 * 설명 :채팅 서버 메세지 전송 스레드
 * </pre>
 * 
 * @since : 2018. 12. 28.
 * @author : tobby48
 * @version : v1.0
 */
public class ServerThread extends Thread{
    private Socket socket;
    private DrawingServer server;
    private OutputStream os;
    
    public ServerThread(DrawingServer server, Socket s){
        this.server = server;
        this.socket = s;
        System.out.println("클라이언트 연결 : " + s.getInetAddress().getHostAddress());
    }
    
    public void run(){
        InputStream is = null;
        DataInputStream dis = null;
        
        try{
            is = socket.getInputStream();
            dis = new DataInputStream(is);
            String line;
            while(true){
                line = dis.readUTF();
                //	서버로 들어온 메세지는 접속된 모든 클라이언트에게 전송
                System.out.println(line);
                server.broadcast(line);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{ is.close(); } catch(IOException e) {}
            try{ socket.close(); } catch(IOException e) {}
        }
    }
    
    public void sendMessage(String message){
        try {
            os = socket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(message);
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}