記錄

JAVA) 네트워크(채팅 예제 구현) 본문

Computer language/JAVA

JAVA) 네트워크(채팅 예제 구현)

surhommejk 2018. 2. 21. 17:06





server

package Practice;

import java.util.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

public class server {

    public static void main(String[] args) {
        try {

            ServerSocket serversocket = new ServerSocket(9000);
            
            /*
             * ServerSocket
             * public ServerSocket(int port) throws IOException
             *
             * Creates a server socket, bound to the specified port.
             * A port number of 0 means that the port number is automatically allocated,
             * typically from an ephemeral port range.
             */
            System.out.println("Client의 접속을 기다리고 있습니다..");

            Socket socket = serversocket.accept();
            /*
             * accept public Socket accept() throws IOException
             *
             * Listens for a connection to be made to this socket and accepts it.
             * The method blocks until a connection is made.
             *
             * Returns:the new Socket
             */

/*
Seversocket은 생성시 파라미터로 받은 포트를 바라보고 있고
.accept() 실행시 바라보고 있던 포트에 마중을 나가서 listen을 하고 있다가
client 측에서 Socket을 생성하면서 접속을 시도하면

1) 새로운 Socket을 생성해서

2) 찾아온 client socket signal과 자신이 return으로 만드는 socket을 연결해주고

역할은 끝이난다

*/


            new read_S(socket).start();
            new write_S(socket).start();

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

    }

}

class read_S extends Thread {

    Socket socket;

    public read_S(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        DataInputStream dis = null;
        try {

            dis = new DataInputStream(socket.getInputStream());

            while (true) {
                
                // POINT) client가 write 하면 동작한다
                // readUTF는 상대가 입력하지 않으면 계속 대기한다(스캐너처럼)
                // while이 쓸데없이 계속 돌지 않는 이유다
                String msg = dis.readUTF();
                System.out.println();
                System.out.println("상대방 msg : " + msg);

                if (msg.equals("exit"))
                    break;

            }

            /*
             * A data input stream lets an application read primitive Java data types from
             * an underlying input stream in a machine-independent way. An application uses
             * a data output stream to write data that can later be read by a data input
             * stream.
             */

            /*
             * DataInputStream public DataInputStream(InputStream in)
             *
             * Creates a DataInputStream that uses the specified underlying InputStream.
             *
             * Parameters:in - the specified input stream
             */

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

class write_S extends Thread {

    Socket socket;

    public write_S(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        Scanner sc = new Scanner(System.in);
        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(socket.getOutputStream());

            while (true) {
                System.out.print("할 말 : ");
                String msg = sc.nextLine();
                dos.writeUTF(msg);

                if (msg.equals("exit"))
                    break;

            }

        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}



client

package Practice;

import java.util.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

public class client {

    public static void main(String[] args) {
        try {
            Socket socket = new Socket("192.168.0.xx", 9000);
            System.out.println("접속완료");

            new read_C(socket).start();
            new write_C(socket).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
        /*
         * Socket
         * public Socket(String host, int port) throws UnknownHostException, IOException
         *
         * Creates a stream socket and connects it to the specified port number on the
         * named host. If the specified host is null it is the equivalent of specifying
         * the address as InetAddress.getByName(null). In other words, it is equivalent
         * to specifying an address of the loopback interface.
         *
         * If the application has specified a server socket factory, that factory's
         * createSocketImpl method is called to create the actual socket implementation.
         * Otherwise a "plain" socket is created.
         *
         * If there is a security manager, its checkConnect method is called with the
         * host address and port as its arguments. This could result in a
         * SecurityException.
         *
         * Parameters: host - the host name, or null for the loopback address.port - the
         * port number.
         */

    }

}

class read_C extends Thread {
    Socket socket;

    public read_C(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(socket.getInputStream());
            while (true) {
                
                // POINT) server가 write 하면 동작한다
                // readUTF는 상대가 입력하지 않으면 계속 대기한다(스캐너처럼)
                // while이 쓸데없이 계속 돌지 않는 이유다
                String msg = dis.readUTF();
                    System.out.println();
                    System.out.println("상대방 msg : " + msg);
                if (msg.equals("exit"))
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

class write_C extends Thread {
    Socket socket;

    public write_C(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        DataOutputStream dos = null;
        Scanner sc = new Scanner(System.in);
        try {
            dos = new DataOutputStream(socket.getOutputStream());

            while (true) {
                System.out.print("할 말 : ");
                String msg = sc.nextLine();

                dos.writeUTF(msg);

                if (msg.equals("exit"))
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}


※ Thread를 main위에 두 개를 올려서 시작했는데 사실 main도 Thread라서 결과적으로 총 Thread가 세 개가 된다. 메인을 read로 쓰든 write으로 쓰든 하나로 사용하고 남는 기능 하나를 Thread만들어서 돌려도 된다. (main을 포함하여 총 두 개의 Thread만으로도 구현이 가능하다는 의미)


※ Seversocket은 생성시 파라미터로 받은 포트를 바라보고 있고

.accept() 실행시 바라보고 있던 포트에 마중을 나가서 listen을 하고 있다가

client 측에서 Socket을 생성하면서 접속을 시도하면


1) 새로운 Socket을 생성해서

2) 찾아온 client socket signal과 자신이 return으로 만드는 socket을 연결해주고


역할은 끝이난다



'Computer language > JAVA' 카테고리의 다른 글

JAVA) JDBC  (0) 2018.03.06
JAVA) HashMap에서의 순서  (0) 2018.02.21
JAVA) HashMap의 value들을 ArrayList에 넣기  (0) 2018.02.21
JAVA) Thread  (0) 2018.02.20
JAVA) 직렬화  (0) 2018.02.20
Comments