서버 소스이다.

포트번호를 설정을한다. (기존의 사용하는 포트번호와 겹치지 않게 조심!)

스트림 객체 생성하고 스레드 시작한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
 
// To create UI and listen to client access
public class EightServer extends JFrame implements Runnable {
 
    static final int PORT = 8880// 서버프로그램의 포트번호
    Socket socket;
    ServerSocket serverSocket; // 서버소켓
    DataOutputStream dos;
    DataInputStream dis;
    ArrayList<User> userArray; // 서버에 접속한 사용자들
    ArrayList<Room> roomArray; // 서버가 열어놓은 채팅방들
 
    int sizeX = 600, sizeY = 600;
    Dimension whole, part;
    int xPos, yPos;
    JTextArea jta;
    ImageIcon icon;
    JPanel jp;
 
    EightServer() {
        userArray = new ArrayList<User>();
        roomArray = new ArrayList<Room>();
        setTitle("Octopus Server");
        setSize(sizeX, sizeY);
 
        icon = new ImageIcon("icon2.png");
        this.setIconImage(icon.getImage());//타이틀바에 이미지넣기
        
        jta = new JTextArea();
        jp = new JPanel();
 
        jp.setLayout(new GridLayout(12)); // 그리드 레이아웃
        jta.setEditable(false); // 에디팅 불가
        jta.setLineWrap(true); // 자동줄바꿈
 
        JScrollPane jsp = new JScrollPane(jta); // 텍스트에어리어에 스크롤 추가
        jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jp.add(jsp);// 패널에 스크롤 붙임
        jta.setText("Server Start...1\n");
 
        add(jp); // 프레임에 패널 붙임
 
        // 윈도우 위치 계산
        whole = Toolkit.getDefaultToolkit().getScreenSize();
        part = this.getSize();
        xPos = (int) (whole.getWidth() / 2 - part.getWidth() / 2);
        yPos = (int) (whole.getHeight() / 2 - part.getHeight() / 2);
 
        setLocation(xPos, yPos);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
 
    public static void main(String[] args) {
        // Create server UI
        System.out.println("Server start...2");
        EightServer server = new EightServer();
        Thread thread = new Thread(server);
        thread.start();
    }
 
    @Override
    public void run() {
        // 클라이언트 대기 모드
 
        // 서버소켓 생성
        try {
            InetAddress addr = InetAddress.getLocalHost(); // 로컬호스트 주소
            serverSocket = new ServerSocket(PORT); // 서버소켓 생성
            jta.append(PORT + "번 포트로 정상적으로 소켓이 생성되었습니다.\n" + "현재 열린 서버의 IP 주소는 " 
                            + addr.getHostAddress().toString() + "입니다. \n");
        } catch (IOException e1) {
            e1.printStackTrace();
            jta.append("서버 소켓 생성에러\n");
        }
 
        while (true) {
            socket = null;
            dis = null;
            dos = null;
            try {
                // 무한반복, 입출력 에러가 나거나 프로그램이 종료될 때까지 실행
                socket = serverSocket.accept(); // 클라이언트 접속 대기
                jta.append("클라이언트 " + socket.getInetAddress().getHostAddress()    + "가 접속되었습니다.\n");
 
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                jta.append("클라이언트 접속에러\n");
            }
            try {
                // 스트림 객체 생성
                dis = new DataInputStream(socket.getInputStream());
                dos = new DataOutputStream(socket.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    dis.close();
                    dos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    jta.append("스트림 해제에러\n");
                }
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    jta.append("소켓 해제에러\n");
                }
                jta.append("스트림 생성에러\n");
            }
            User person = new User(dis, dos); // 가명의 사용자 객체 생성
            person.setIP(socket.getInetAddress().getHostName()); // 아이피주소 설정 부여
 
            Thread thread = new Thread(new ServerThread(jta, person, userArray,    roomArray));
            thread.start(); // 스레드 시작
        }
    }
}
cs


이러한 창을 띄워 잘못되는점이나 오류를 확인하게 하였다.

'* Project > Chatting_Pro' 카테고리의 다른 글

채팅 프로그램 마무리  (0) 2016.09.07
대기화면 소스(WaitRoomUI.java)  (0) 2016.09.07
회원 수정 DB / 회원 탈퇴 DB  (1) 2016.09.07
로그인 체크 DB  (1) 2016.09.07
회원가입 DB / 메시지박스  (1) 2016.09.07

25일차 강의 정리


스레드 스케줄링

Thread.MIN_PRIORITY => 1

Thread.NORM_PRIORITY => 5

Thread.MAX_PRIORITY => 10

1~10 까지의 우선순위가 있어서, 높을 수록 실행 할 확률이 높아 진다고 보면된다.(먼저실행할 확률)

스케쥴링의 두번째로는 join()이 있어서, 우선순위로 지정한 메소드 먼저 끝낼수있게 한다.

소스1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Pm00 extends Thread{
    Pm00 me;
    public Pm00(String name){
        super(name);
    }
    void setMe(Pm00 me){
        this.me = me;
    }
    @Override
    public void run() {
        try{
            if(me!=null)me.join();
        }catch(InterruptedException ee){
            ee.printStackTrace();
        }
        
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.getName()+" 스레드 순위 "+this.getPriority());        //디폴트로 5,항상동일
        }
    }
}
 
public class Ex00 {
    public static void main(String[] args) {
        Pm00 me1 = new Pm00("1번");
        Pm00 me2 = new Pm00("2번");
        Pm00 me3 = new Pm00("3번");
        
        me1.setPriority(Thread.MIN_PRIORITY);//1    //디폴트 순위는 무조건 5로시작
        me2.setPriority(Thread.NORM_PRIORITY);//5    //1(낮은순위) ~ 10(높은 순위)
        me3.setPriority(Thread.MAX_PRIORITY);//10    //우선순위를 높게주면 실행기회가높아진다
        
        me1.start();
        me2.setMe(me1);    //me1이끝날때까지 기다린다
        me2.start();
        me3.setMe(me2);    //me2이끝날때까지 기다린다
        me3.start();
 
        System.out.println("main end.");
    }
}
cs

결과1

소스2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Am02 implements Runnable{
    
    @Override
    public void run() {
        for (int i = 0; i < 6; i++) {
            Thread thr = Thread.currentThread();
            thr.setPriority(Thread.MIN_PRIORITY+i);
            try {
                thr.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(thr.getName()+":"+thr.getPriority());
        }
    }
}
public class Ex02 {
    public static void main(String[] args) {
        Am02 am2 = new Am02();
        
        Thread thr1 = new Thread(am2,"th1");
        Thread thr2 = new Thread(am2,"th2");
        Thread thr3 = new Thread(am2,"th3");
 
        try{
            thr1.start();
            thr1.join(100);        //( )시간동안 thr1을 실행
            thr2.start();
            thr2.join();
            thr3.start();
            thr3.join();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("main end");
        
    }
}
cs

결과2


동기화

소스

특정블록의 동기화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Bank {
    int money;
 
    public Bank() {
        money = 0;
    }
}
class ATM extends Thread{
    Bank bank;
    public ATM(Bank bank){
        this.bank = bank;
    }
    
    //특정 블록의 동기화방법
    @Override
    public void run() {
        add(1000);
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        del(500);
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        del(300);
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        del(200);
    }
    void add(int money){
        synchronized (bank){        //임계영역코딩(동기화할 객체 또는 동기화할 클래스명)
            this.bank.money+=money;
            System.out.println("cd입금: "+money+"원, 은행잔고: "+this.bank.money+"원");
        }
    }//add end
    synchronized void del(int money){
        synchronized (bank) {
            if (this.bank.money >= 0 && this.bank.money >= money) {
                this.bank.money -= money;
                System.out.println("cd출금: " + money + "원, 은행잔고: "
                        + this.bank.money + "원");
            } else {
                System.out.println("잔고부족");
            }
        }
    }//del end
}//ATM class end
 
public class Ex03 {
    public static void main(String[] args) {
        Bank bank = new Bank();
        ATM atm1 = new ATM(bank);
        ATM atm2 = new ATM(bank);
        ATM atm3 = new ATM(bank);
 
        System.out.println("잔고 : "+ bank.money+"원");
        atm1.start();
        atm2.start();
        atm3.start();
        try {
            atm1.join();
            atm2.join();
            atm3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("잔고 : "+ bank.money+"원");
    }
 
}
cs

메서드 동기화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Bank {
    int money;
 
    public Bank() {
        money = 0;
    }
 
    // 메서드 동기화방법
      synchronized void add(int money) { 
        this.money += money;
        System.out.println("cd입금: " + money + "원, 은행잔고: " + this.money + "원");
 
    }// add end
 
    synchronized void del(int money) {
        if (this.money >= 0 && this.money >= money) {
            this.money -= money;
            System.out.println("cd출금: " + money + "원, 은행잔고: " + this.money + "원");
        } else {
            System.out.println("잔고부족");
        }
    }// del end
}
class ATM extends Thread{
    Bank bank;
    public ATM(Bank bank){
        this.bank = bank;
    }
    
    //메서드 동기화방법
     @Override
    public void run() {
        bank.add(1000);
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        bank.del(500);
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        bank.del(300);
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        bank.del(200);
    }
}//ATM class end
 
public class Ex03 {
    public static void main(String[] args) {
        Bank bank = new Bank();
        ATM atm1 = new ATM(bank);
        ATM atm2 = new ATM(bank);
        ATM atm3 = new ATM(bank);
 
        System.out.println("잔고 : "+ bank.money+"원");
        atm1.start();
        atm2.start();
        atm3.start();
        try {
            atm1.join();
            atm2.join();
            atm3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("잔고 : "+ bank.money+"원");
    }
}
cs

결과

3개의 스레드가 동시에돌아도 문제없다.

소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class ATM2 implements Runnable{
    int money;
    
    public ATM2() {this.money=0;}
    
    @Override
    public void run() {
        add(1000);
        try {
            Thread.currentThread().sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        del(500);
        try {
            Thread.currentThread().sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        del(300);
        try {
            Thread.currentThread().sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        del(200);
    }
 
    void add(int money){
        synchronized (this) {
            this.money+=money;
            System.out.println(Thread.currentThread().getName());
            System.out.println("cd입금-"+money+"원, 은행잔고:"+this.money+"원");
        }
    }
    void del(int money){
        synchronized (this) {
            if(this.money>=0 && this.money>=money){
                this.money -=money;
                System.out.println(Thread.currentThread().getName());
                System.out.println("cd출금-"+money+"원, 은행잔고:"+this.money+"원");
            }else{
                System.out.println("잔고 부족");
            }
        }
    }
}
 
public class Ex05 {
    public static void main(String[] args) {
        ATM2 bank = new ATM2();
        System.out.println("잔고:"+bank.money+"원");
        Thread atm1 = new Thread(bank,"ATM1");
        Thread atm2 = new Thread(bank,"ATM2");
        Thread atm3 = new Thread(bank,"ATM3");
        atm1.start();
        atm2.start();
        atm3.start();
        try {
            atm1.join();
            atm2.join();
            atm3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("잔고:"+bank.money+"원");
    }
 
}
cs

결과

*state...>?


'* Programming > JAVA' 카테고리의 다른 글

SMS 참고 사이트  (0) 2018.03.08
DAY25 IO  (0) 2016.08.11
DAY24 스레드  (0) 2016.08.08
DAY24 제네릭2(메소드제네릭,와일드카드)  (0) 2016.08.08
DAY23 제네릭1  (0) 2016.08.08

24일차 강의 정리


스레드


소스1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Pm01 extends Thread{        //Thread 상속
    @Override
    public void run(){
        for (int i = 0; i < 6; i++) {
            try {
                Thread.sleep(1000);    //1000분의 1초 휴식->1초
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("스레드로 실행");
        }
    }
}
 
public class Ex01 {
 
    public static void main(String[] args) {
        // 스레드
        System.out.println("main start");
        Pm01 pm01 = new Pm01();
        pm01.start();        //새로운 스레드로  run()실행
        pm01 = new Pm01();    //새로운 객체
        pm01.start();        //새로운 스레드로  run()실행
        
        for (int i = 0; i < 6; i++) {
            try {
                Thread.sleep(1000);     //휴식->1초
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("main i : "+i);
        }
        System.out.println("main end");
        
    }//main end
}//class end
cs

결과1

소스2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Ex02 extends Thread{
 
    public static void main(String[] args) {
        System.out.println("main start");
        Ex02 me = new Ex02();    //이객체를 통한 두번째 스레드
        me.start();                //run()이 실행
        for (int i = 0; i < 10; i++) {
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("main() i: "+i);
        }
        System.out.println("main end.....");
 
    }
    @Override
    public void run(){    //main 에서 실행해서 run을 스레드로 사용
        for (int i = 0; i < 10; i++) {
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("new Ex02 thread run() i: "+i);
        }
        System.out.println("run end...........");
    }
}
cs

결과2

소스3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Pm44 extends Thread{
    public Pm44(String name) {
        super(name);
    }
    @Override
    public void run() {
        for(int i=0; i<5; i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.getName());
        }
    }
}
 
class Pm04 implements Runnable {    //인터페이스로 상속받아서 스레드 사용하기
 
    @Override
    public void run() {
        for(int i=0; i<5; i++){
            try {
                Thread.sleep(1000);        //해당 스레드를 1/1000잠시 휴식(1s)
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Thread thr = Thread.currentThread();
            System.out.println(thr.getName());
        }
    }
    
}
 
public class Ex04 {
 
    public static void main(String[] args) {
        Pm04 pm4 = new Pm04();
        Thread thread = new Thread(pm4,"스레드 추가");        //""가 변경된 스레드 이름
        thread.start();
        Pm44 pm44 = new Pm44("상속을 통한");
        pm44.start();
        for(int i=0; i<5; i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            System.out.println(Thread.currentThread());        //[스레드명, 스케줄링, ..?뭔단?]
            System.out.println(Thread.currentThread().getName());
        }
    }
 
}
cs

결과3



'* Programming > JAVA' 카테고리의 다른 글

DAY25 IO  (0) 2016.08.11
DAY25 스레드 스케줄링&동기화  (0) 2016.08.08
DAY24 제네릭2(메소드제네릭,와일드카드)  (0) 2016.08.08
DAY23 제네릭1  (0) 2016.08.08
DAY22 큐&스택  (0) 2016.08.04

+ Recent posts