Socket 프로그래밍으로 서버의 몇 문자를 읽고 로컬 디스플레이에 쓰기

2998 단어
서버
package com.zhangry.interview.java.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket ss;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    public Server(){
         try {
            ss = new ServerSocket(8888);
            while(true){
                socket = ss.accept();
                String remoteIP =  socket.getInetAddress().getHostAddress();
                String remotePort = ":"+socket.getLocalPort();
                System.out.println("  ! IP :"+remoteIP+remotePort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = in .readLine();
                System.out.println("  :"+ line);
                out= new PrintWriter(socket.getOutputStream(),true);
                out.println(" !");
                out.close();
                in.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args){
        new Server();
    }
}

 
클라이언트
package com.zhangry.interview.java.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    Socket socket;
    BufferedReader in;
    PrintWriter out;
    public Client(){
        try {
            System.out.println("Try to connect to 127.0.0.1:8888");
            socket = new Socket("127.0.0.1",8888);
            System.out.println(" ");
            System.out.println(" :");
            BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(socket.getOutputStream(),true);
            out.println(line.readLine());
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(in.readLine());
            out.close();
            in.close();
            socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args){
        new Client();
    }
}

좋은 웹페이지 즐겨찾기