[Java/CodingPractice]04. CodingPractice04



소켓통신 1:1 채팅


Guest.java

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
package com.tcp.chat.client;
 
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
 
import com.tcp.chat.util.Receiver;
import com.tcp.chat.util.Sender;
 
public class Guest extends Thread {
 
    private Socket socket;
    private Sender sender;
    private Receiver receiver;
 
    /// Constructor
    public Guest(String host, int port, String name, Scanner scanner) throws IOException{
        super();
        this.socket = new Socket(host, port);
        this.sender = new Sender(this.socket, name, scanner);
        this.receiver = new Receiver(this.socket);
    }
    
    @Override
    public void run() {
        sender.start();
        receiver.start();
    }
 
    public static void main(String[] args) throws IOException {
        
        String host = "localhost";
        int port = 8080;
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("채팅할 아이디를 입력하세요.");
        String name = scanner.nextLine();
        
        Guest guest = new Guest(host, port, name, scanner);
        System.out.println("채팅방에 접속함. 호스트 IPv4 : " + host + ". \"exit\" 입력시 종료함. ");
        
        guest.start();
        
    }
}
cs


ChatSocket.java

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
package com.tcp.chat.server;
 
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
 
import com.tcp.chat.util.Receiver;
import com.tcp.chat.util.Sender;
 
public class ChatSocket extends Thread {
 
    private Socket socket;
    private Sender sender;
    private Receiver receiver;
 
    // / Constructor
    public ChatSocket(Socket socket, String name, Scanner scanner) throws IOException {
        super();
        this.socket = socket;
        this.receiver = new Receiver(this.socket);
        this.sender = new Sender(this.socket, name, scanner);
        System.out.println("게스트가 접속함. 게스트 IPv4 : " + socket.getLocalAddress());
    }
 
    @Override
    public void run() {
        sender.start();
        receiver.start();
    }
    
    public static void main(String args[]) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        
        System.out.println("1:1 채팅방 만듬. \"exit\"입력시 종료함. 채팅할 아이디를 입력하세요.");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        
        ChatSocket tcpIpSocket = new ChatSocket(serverSocket.accept(), name, scanner);
        tcpIpSocket.start();
        serverSocket.close();
    }
 
}
cs


Receiver.java

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
package com.tcp.chat.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import com.tcp.chat.util.Receiver;
import com.tcp.chat.util.Sender;
public class ChatSocket extends Thread {
    private Socket socket;
    private Sender sender;
    private Receiver receiver;
    // / Constructor
    public ChatSocket(Socket socket, String name, Scanner scanner) throws IOException {
        super();
        this.socket = socket;
        this.receiver = new Receiver(this.socket);
        this.sender = new Sender(this.socket, name, scanner);
        System.out.println("게스트가 접속함. 게스트 IPv4 : " + socket.getLocalAddress());
    }
    @Override
    public void run() {
        sender.start();
        receiver.start();
    }
    
    public static void main(String args[]) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        
        System.out.println("1:1 채팅방 만듬. \"exit\"입력시 종료함. 채팅할 아이디를 입력하세요.");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        
        ChatSocket tcpIpSocket = new ChatSocket(serverSocket.accept(), name, scanner);
        tcpIpSocket.start();
        serverSocket.close();
    }
}
cs


Sender.java

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
package com.tcp.chat.util;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
 
public class Sender extends Thread{
    private PrintWriter printWriter;
    private Scanner scanner;
    private String chatToReceiver;
    private String senderName;
 
    /// Constructor
    public Sender(Socket socket, String senderName, Scanner scanner) throws IOException{
        super();
        this.printWriter = new PrintWriter(socket.getOutputStream());
        this.scanner = scanner;
        this.senderName = senderName;
    }
    
    public void closeAll() throws IOException{
        printWriter.close();
        scanner.close();
    }
    
    public void sendMessage(String message){
        printWriter.println("[ "+ senderName +" ] : " + message);
        System.out.println("[ "+ senderName +" ] : " + message);
        printWriter.flush();
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            while ((chatToReceiver = scanner.nextLine()) != null) {
                
                if (chatToReceiver.equals("exit")) {
                    break;
                }
                sendMessage(chatToReceiver);
            }
            closeAll();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
cs


[Java/CodingPractice]03. CodingPractice03


그룹 채팅.


Host.java

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
package com.chat.server;
 
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
import com.chat.util.BroadCast;
import com.chat.util.GuestVO;
 
public class Host extends Thread {
    
    private ServerSocket serverSocket;
    private Socket       socket;
    private List<GuestVO>  guests;
    private int          port;
    
    public Host(int port) throws IOException  {
        super();
        this.port = port;
        this.serverSocket = new ServerSocket(this.port);
        guests = new ArrayList<GuestVO>();
        Collections.synchronizedList(guests);
    }
    
    @Override
    public void run(){
        System.out.println("채팅방을 켰음. 게스트들을 대기중... ");
        try {
            while(true){
                BroadCast broadCast = new BroadCast(serverSocket.accept(), this.guests);
                broadCast.start();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
 
    public static void main(String args[]) throws IOException{
        new Host(8080).start();
    }
    
    
 
}
 
cs


BroadCast.java

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
package com.chat.util;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
 
public class BroadCast extends Thread {
    
    private BufferedReader bufferedReader;
    private PrintWriter printWriter;
    private String chatFromReceiver;
    private List<GuestVO> guests;
    
    /// Constructor
    public BroadCast(Socket socket, List<GuestVO> guests) throws IOException{
        super();
        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        printWriter = new PrintWriter(socket.getOutputStream());
        this.guests = guests;
    }
    
    public void closeAll() throws IOException{
        bufferedReader.close();
        printWriter.close();
    }
    
    public void sendToAll(String message){
        for(GuestVO guest: guests){
            guest.getPrintWriter().println(message);
            guest.getPrintWriter().flush();
        }
    }
    
    @Override
    public void run() {
        GuestVO guest = null;
        // TODO Auto-generated method stub
        try {
            
            guest = new GuestVO(printWriter, bufferedReader.readLine());
            System.out.println("\"" + guest.getName() + "\"님이 접속함.");
            guests.add(guest);
            sendToAll("\"" + guest.getName() + "\" 님이 접속함.");
            
            while ((chatFromReceiver = bufferedReader.readLine()) != null){
                System.out.println("[ "+ guest.getName() +" ] : "+ chatFromReceiver);
                sendToAll("[ "+ guest.getName() +" ] : "+ chatFromReceiver);
            }
            closeAll();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            System.out.println("\"" + guest.getName() + "\"님이 나감.");
            sendToAll("\"" + guest.getName() + "\"님이 나감.");
            guests.remove(guest);
        }
    }
}
 
cs


GuestVO.java

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
package com.chat.util;
 
import java.io.PrintWriter;
 
public class GuestVO {
    
    private PrintWriter printWriter;
    private String name;
    
    public GuestVO(PrintWriter printWriter, String name) {
        super();
        this.printWriter = printWriter;
        this.name = name;
    }
 
    public PrintWriter getPrintWriter() {
        return printWriter;
    }
 
    public void setPrintWriter(PrintWriter printWriter) {
        this.printWriter = printWriter;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
    
    
}
 
cs


Guest.java

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
package com.chat.client;
 
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
 
import com.chat.util.Receiver;
import com.chat.util.Sender;
 
public class Guest extends Thread {
    
    private Socket socket;
    private Sender sender;
    private Receiver receiver;
    private Scanner scanner;
 
    /// Constructor
    public Guest(String iPv4, int port) throws IOException {
        this.socket = new Socket(iPv4, port);
        this.scanner = new Scanner(System.in);
        this.sender = new Sender(socket, scanner);
        this.receiver = new Receiver(socket);
    }
 
    @Override
    public void run() {
        sender.start();
        receiver.start();
    }
    
    public static void main(String[] args) throws IOException{
        Guest guest = new Guest("localhost"8080);
        guest.start();
    }
    
}
 
cs


Receiver.java

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
package com.chat.util;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
 
public class Receiver extends Thread {
    private BufferedReader bufferedReader;
    private String chatFromReceiver;
 
    /// Constructor
    public Receiver(Socket socket) throws IOException{
        super();
        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    
    public void closeAll() throws IOException{
        bufferedReader.close();
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            while ((chatFromReceiver = bufferedReader.readLine()) != null){
                System.out.println(chatFromReceiver);
            }
            closeAll();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
 
cs


Sender.java

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
package com.chat.util;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
 
public class Sender extends Thread{
    private PrintWriter printWriter;
    private Scanner scanner;
    private String chatToReceiver;
 
    /// Constructor
    public Sender(Socket socket, Scanner scanner) throws IOException{
        super();
        this.printWriter = new PrintWriter(socket.getOutputStream());
        this.scanner = scanner;
    }
    
    public void closeAll() throws IOException{
        printWriter.close();
        scanner.close();
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        
        System.out.println("서버에 접속함. 이름 입력.");
        printWriter.println(scanner.nextLine());
        printWriter.flush();
        
        try {
            while ((chatToReceiver = scanner.nextLine()) != null) {
                
                if (chatToReceiver.equals("exit")) {
                    break;
                }
                printWriter.println(chatToReceiver);
                printWriter.flush();
            }
            closeAll();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
 
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
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
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
 
public class CodingPractice02 {
 
    public static boolean isOverlapped(Circle c1, Circle c2){
        double sumOfR = c1.getR() + c2.getR();
        double distance = Math.sqrt(Math.pow(c1.getX()-c2.getX(),2+ Math.pow(c1.getY() - c2.getY(), 2));
        
        if(distance < sumOfR){
            return true;
        }else{
            return false;
        }
        
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Scanner scan = new Scanner(System.in);
        int theNumberOfCircle=-1;
        
        // set the number of circles
        while(theNumberOfCircle < 0){            
            System.out.println("Please input the number of circles.");
            theNumberOfCircle = scan.nextInt();
            
            if(theNumberOfCircle<0){
                System.out.print("Worng value. ");
            }
        }
        
        List<Circle> circles = new ArrayList<Circle>(theNumberOfCircle);
        List<Integer> circlesId = new ArrayList<Integer>(theNumberOfCircle);
        
        // input circles
        for(int i = 0 ; i < theNumberOfCircle ; i++){
            
            Circle tempCircle = new Circle(scan.nextInt(), scan.nextDouble(), scan.nextDouble(), scan.nextDouble());
            
            // validation check
            // range of circle
            if(
                    (1 > tempCircle.getId() || tempCircle.getId() > 300||
                    (-10000 > tempCircle.getX() || tempCircle.getX() > 10000||
                    (-10000 > tempCircle.getY() | tempCircle.getY() > 10000||
                    (0 >= tempCircle.getR() || tempCircle.getR() > 10000)
              ){
                System.out.println("Worng value");
                i--;
                continue;
            }else if(i > 0){
                // ID duplication check
                if(circlesId.contains(tempCircle.getId())){
                    System.out.println("Worng value");
                    i--;
                    continue;
                }
            }
            
            circles.add(tempCircle);
            circlesId.add(tempCircle.getId());
            
        }
        
        
        // printing overlapped circles
        for(int i = 0 ; i < circles.size() ; i ++){
            for(int j = i ; j < circles.size() ; j++){
                if(i==j){
                    continue;
                }else{
                    if(isOverlapped(circles.get(i), circles.get(j))){
                        System.out.println(circles.get(i).getId() + ", " + circles.get(j).getId());                                            
                    }
                }
            }
        }
        
        
        
    }
 
}
 
class Circle{
    
    private int    id;
    private double x;
    private double y;
    private double r;
    
    
    public Circle() {
        super();
    }
 
    public Circle(int id, double x, double y, double r) {
        super();
        this.id = id;
        this.x = x;
        this.y = y;
        this.r = r;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public double getX() {
        return x;
    }
    public void setX(double x) {
        this.x = x;
    }
    public double getY() {
        return y;
    }
    public void setY(double y) {
        this.y = y;
    }
    public double getR() {
        return r;
    }
    public void setR(double r) {
        this.r = r;
    }
    
}
cs


Click here to Github


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
public class CodingPractice01 {
    
    // 주어진 정수를 뒤집어서 출력
    // Ex : 46312 => 21364
    public static int getReversedInteger(int val){
        StringBuffer returnVal = new StringBuffer();
        int length = String.valueOf(val).length();
        
        for(int i = 0 ; i < length ; i ++){
            returnVal.append(val%10);
            val /= 10;
        }
        
        return Integer.parseInt(returnVal.toString());
    }
    
    // 배열을 오름차순으로 정렬하고 중간값 출력
    // 입력받은 수들의 개수가 짝수면 두 개의 중간값의 평균을 출력
    // Ex : 10, 2, 101, 90 => 50
    public static double getMedian(int[] val){
        int indexMin, temp;
        
        // Selection sort
        for(int i = 0 ; i < val.length; i++){
            indexMin = 0;
            for(int j = i; j < val.length ; j++){
                if(val[indexMin] > val[j]){
                    indexMin = j;
                }
            }
            temp = val[indexMin];
            val[indexMin] = val[i];
            val[i] = temp;
        }
        
        if(val.length % 2==0){
            return (val[val.length/2+ val[val.length/2+1])/2;
        }else{
            return val[val.length/2+1];
        }
        
    }    
    
    // 해당 순번의 피보나치의 값 출력
    // Ex : 2 => 1, 8 => 21
    // no recursive
    public static int getFibonacciNumber(int val){
        
        int prePre = 0;
        int pre = 1;
        int in  = 0;
        
        if(val <= 0){
            return prePre;
        }else if(val == 1){
            return pre;
        }else{
            for(int i = 0 ; i < val-1 ; i ++){
                in = prePre + pre;
                prePre = pre;
                pre = in;
            }
            return pre;
        }
        
    }
    
    public static void main(String args[]){
        System.out.println(getReversedInteger(46312));
        // 21364
        
        int arrayInt[] = {10210190};
        System.out.println(getMedian(arrayInt));
        // 50.0
        
        System.out.println(getFibonacciNumber(8));
        // 21
        
    }
 
}
cs


+ Recent posts

티스토리 툴바