본문 바로가기
안드로이드 자바

[Java][Android] JAVA 1대 1 콘솔 채팅 (client 구현하기)

by teamnova 2022. 4. 3.
728x90

지난주에 이어 이번주는 client 측 소스를 구현해 보겠습니다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;
 
public class TCPClient {
    public static void main(String[] args) {
        // 클라이언트 소켓 생성
        Socket socket = new Socket();
        Scanner sc = new Scanner(System.in);
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStream os = null;
        OutputStreamWriter osw = null;
        PrintWriter pw = null;
      // new InetSocketAddress(InetAddress.getLocalHost() 6077
        try {
            socket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 6077));
            System.out.println("[client] connected with server");
            while (true) {
                is = socket.getInputStream();
                isr = new InputStreamReader(is, "UTF-8");
                br = new BufferedReader(isr);
                os = socket.getOutputStream();
                osw = new OutputStreamWriter(os, "UTF-8");
                pw = new PrintWriter(osw, true);
 
                // 읽는거
                System.out.print(">>");
                String data = sc.nextLine();
                if ("exit".equals(data))
                    break;
                pw.println(data);
                data = br.readLine();
                System.out.println("<< " + data);
            }

 

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (socket != null && !socket.isClosed()) {
                    socket.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            sc.close();
        }
    }
}

 

지난주에 설정해준 포트와 localhost 주소를 입력해 이를 통해 서버 코드와 채팅이 이루어 질 수 있습니다.

 

https://stickode.com/mainlogin.html

 

STICKODE

 

stickode.com