IT 개발노트

소켓을 이용하여 채팅 프로그램 만들기 본문

기초튼튼/JAVA

소켓을 이용하여 채팅 프로그램 만들기

limsungju 2019. 3. 22. 14:08
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
package tcp;
 
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server {
    public static void main(String arg[])
    {
        Socket socket = null;                    //접속한 Client와 통신하기 위한 Socket
        User user = new User();                    //채팅방에 접속해 있는 Client 관리 객체
        ServerSocket server_socket=null;              //Client 접속을 받기 위한 ServerSocket
        
        int count = 0;                            
        Thread thread[]= new Thread[10];             //접속하는 각각의 Client로부터 데이터를 읽어들이고 데이터전송
        
        try {
            server_socket = new ServerSocket(12345);
            //Server의 메인쓰레드는 게속해서 사용자의 접속을 받음
            while(true)
            {
                socket = server_socket.accept();
                //접속 한 사용자와 통신 할 수 있는 socket을 가지는 Receiver 쓰레드를 생성 및 시작.
                thread[count] = new Thread(new Receiver(user,socket));
                thread[count].start();
                count++;
            }
        }catch(Exception e) {};
    }
}


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 tcp;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
 
public class Receiver implements Runnable{
     
    Socket socket;
    DataInputStream in;
    String name;
    User user = new User();
 
    public Receiver(User user,Socket socket) throws Exception
    {
        this.user = user;
        this.socket = socket;
        //접속한 Client로부터 데이터를 읽어들이기 위한 DataInputStream 생성
        in = new DataInputStream(socket.getInputStream());
        //최초 사용자로부터 닉네임을 읽어들임
        this.name = in.readUTF();
        //사용자 추가해줍니다.
        user.AddClient(name, socket);
    }
 
    public void run()
    {
        try
        {
            //Receiver는 사용자로부터 넘어오는 데이터를 읽어와 채팅방에 있는 사용자들에게 전송하는 것을 반복합니다.
            while(true)
            {
                String msg = in.readUTF();
                user.sendMsg(msg , name);
            }
        }catch(Exception e) {
            //Exception이 발생했다는 건 사용자가 접속을 끊었다는 의미입니다. 채팅방에서 사용자를 제거합니다.
            user.RemoveClient(this.name);
        }        
    }
}


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
package tcp;
 
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
 
public class User {
    
    HashMap<String,DataOutputStream> clientmap = new HashMap<String,DataOutputStream>();    //채팅방의 사용자 관리 위한 Hashmap
    
    public synchronized void AddClient(String name,Socket socket)            //채팅방 사용자 추가 및
    {                                                                        //채팅방에 남아있는 사용자에게 접속 소식을 알립니다.
        try {
            sendMsg(name+" 입장하셨습니다.","Server");
            clientmap.put(name, new DataOutputStream(socket.getOutputStream()));
            System.out.println("채팅 참여 인원 : "+clientmap.size());
        }catch(Exception e){}
        
    }
    public synchronized void RemoveClient(String name)  //채팅방 사용자 제거 및 채팅방에 존재하는 Client에게 퇴장 소식을 알림
    {
        try {
            clientmap.remove(name);
            sendMsg(name + " 퇴장하셨습니다.""Server");
            System.out.println("채팅 참여 인원 : "+clientmap.size());
        }catch(Exception e) {}
    }
 
    public synchronized void sendMsg(String msg, String name)throws Exception //채팅방에 있는 사용자에게 메세지를 전송
    {
        Iterator iterator = clientmap.keySet().iterator();
        while(iterator.hasNext())
        {
            String clientname =(String)iterator.next();
            clientmap.get(clientname).writeUTF(name + ":" + msg);
        }
    }
}


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 tcp;
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
 
public class Client {
    public static void main(String[] arg)
    {
        Socket socket = null;            //Server와 통신하기 위한 Socket
        DataInputStream in = null;        //Server로부터 데이터를 읽어들이기 위한 입력스트림
        BufferedReader in2 = null;        //키보드로부터 읽어들이기 위한 입력스트림
        DataOutputStream out = null;    //서버로 내보내기위한 스트림
        
        try {
 
            socket = new Socket("127.0.0.1",12345);    //서버로 접속
            
            in = new DataInputStream(socket.getInputStream());            //서버로부터 데이터 읽어들이기 위한 스트림 생성
            in2 = new BufferedReader(new InputStreamReader(System.in)); //채팅을 위해 사용자 키보드로부터 데이터 읽어들이기 위한 스트림 생성
            out = new DataOutputStream(socket.getOutputStream());        //채팅 내용을 서버로 전송하기 위한 출력 스트림
 
            //채팅에 사용 할 닉네임을 입력받음
            System.out.print("닉네임을 입력해주세요 : ");
            String data = in2.readLine();
            
            //서버로 닉네임을 전송
            out.writeUTF(data);
            //사용자가 채팅 내용을 입력 및 서버로 전송하기 위한 쓰레드 생성 및 시작
            Thread th = new Thread(new Send(out));
            th.start();
        }catch(IOException e) {}
        try {
            //클라이언트의 메인 쓰레드는 서버로부터 데이터 읽어들이는 것만 반복.
            while(true)
            {
                String str2 = in.readUTF();        
                System.out.println(str2);
            }
        }catch(IOException e) {}
    }
}


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
package tcp;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
 
public class Send implements Runnable{
    DataOutputStream out;
    BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
    public Send(DataOutputStream out)
    {
        this.out = out;
    }
    public void run()
    {
        while(true)
        {
            // 클라이언트으이 서브 쓰레드는 키보드로부터 입력받은 내용 서버로 전송하는 것만 계속해서 반복.
            try
            {
                String msg = in2.readLine();    //키보드로부터 입력을 받음
                out.writeUTF(msg);                //서버로 전송
            }catch(Exception e) {}
        }
    }
}



'기초튼튼 > JAVA' 카테고리의 다른 글

트리, 이진트리  (0) 2019.04.24
자바빈(JavaBean)이란?  (0) 2019.04.19
javafx  (0) 2019.03.05
TIME 예제(현재시간부터 일정 시간표시하기)  (0) 2019.02.19
프로세스 호출 예제  (0) 2019.02.19