ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바 인프런 - 간단한 채팅프로그램
    자바/인프런 인강 2018. 2. 16. 16:08

    클라이언트가 서버 소켓에 접속한 뒤 입력한 문장을 서버에서 입력 받는 간단한 채팅 프로그램 


    -서버 소켓


    import java.io.BufferedReader;

    import java.io.InputStreamReader;

    import java.io.PrintWriter;

    import java.net.ServerSocket;

    import java.net.Socket;


    public class MakeServersocket {

    ServerSocket serversocket = null;

    Socket socket = null;

    PrintWriter writer = null;

    BufferedReader reader = null;

    String lineStr;


    public MakeServersocket() {

    try {

    serversocket = new ServerSocket(2000);


    while (true) {

    socket = serversocket.accept();

    System.out.println("클라이언트 요청");


    writer = new PrintWriter(socket.getOutputStream(), true);

    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));


    while ((lineStr = reader.readLine()) != null) {

    writer.write(lineStr);

    System.out.println("input:" + lineStr);

    }


    writer.close();

    reader.close();

    socket.close();


    }


    } catch (Exception e) {

    }

    }


    public static void main(String[] args) {

    new MakeServersocket();

    }


    }




    -클라이언트 소켓


    import java.io.BufferedReader;

    import java.io.InputStreamReader;

    import java.io.PrintWriter;

    import java.net.Socket;


    public class MakeClientsocket {

    Socket socket = null;

    PrintWriter writer = null;

    BufferedReader reader = null;

    public MakeClientsocket() {

    try {

    socket = new Socket("localhost", 2000);

    writer = new PrintWriter(socket.getOutputStream(), true);

    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String str = null;

    BufferedReader sReader = new BufferedReader(new InputStreamReader(System.in));

    while((str = sReader.readLine()) !=null) {

    writer.println(str);

    System.out.println("output:" + str);

    }

    writer.close();

    reader.close();

    sReader.close();

    socket.close();

    } catch (Exception e) {

    }

    }


    public static void main(String[] args) {

    new MakeClientsocket();

    }







    }