码迷,mamicode.com
首页 > 其他好文 > 详细

socket编程3-Handler

时间:2014-12-12 01:14:09      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:io   os   sp   java   on   bs   ad   as   line   

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

标签:io   os   sp   java   on   bs   ad   as   line   

原文地址:http://www.cnblogs.com/stay-sober/p/4158801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!