首页 > 代码库 > socket编程3-Handler

socket编程3-Handler

package Chapter3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Handler implements Runnable {
    private Socket socket;

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

    public void run() {
        try {
            System.out.println("新连接开始" + socket.getInetAddress() + ":"
                    + socket.getPort());
            BufferedReader br = getReader(socket);
            PrintWriter pw = getWriter(socket);
            String msg=null;
            while((msg=br.readLine())!=null){
                System.out.println(msg);
                pw.println(echo(msg));
                if(msg=="bye"){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(socket!=null)
                try {
                    socket.close();
                    System.out.println("连接已关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    private String echo(String msg) {
        return "echo" + msg;
    }

    private BufferedReader getReader(Socket socket) throws IOException {

        InputStream socketIn = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(socketIn));
        return br;
    }

    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOut = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(socketOut, true);
        return pw;
    }
}

socket编程3-Handler