socket 베이스

2376 단어
서버:
public class Server {
    public static void main(String [ ] args){
        try {
            //1、 
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("------- --------");

            //2、 
            Socket socket = serverSocket.accept();
            System.out.println(" "+ socket.getInetAddress().getHostAddress()+" ");

            //3、 , 
            InputStream inputStream = socket.getInputStream();// 
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);// 
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);// 
            String line = null;
            while ((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }
            socket.shutdownInput();

            //4、 , 
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.write(" !");
            printWriter.flush();
            socket.shutdownOutput();

            //5、 
            socket.close();
            serverSocket.close();

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

클라이언트
public class Client {
    public static void main(String [] args){
        try {
            //1、 socket, 
            Socket socket = new Socket("localhost",8888);

            //2、 , 
            OutputStream outputStream = socket.getOutputStream();// 
            PrintWriter printWriter = new PrintWriter(outputStream);// 
            printWriter.write(" :123;  :123");
            printWriter.flush();
            socket.shutdownOutput();

            //3、 , 
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;
            while((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }
            socket.shutdownInput();

            //4、 
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

좋은 웹페이지 즐겨찾기