当前位置: 代码迷 >> J2SE >> Java Socket 阻塞有关问题 求解
  详细解决方案

Java Socket 阻塞有关问题 求解

热度:97   发布时间:2016-04-23 21:17:43.0
Java Socket 阻塞问题 求解
服务器端

public class DayTimeServer {

    public static void main(String[] args){

        ServerSocket server=null;
        try {
            //服务器端8080端口
            server=new ServerSocket(8080);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return;
        }


        int i=0;
        while(true){
            Socket socket = null;
            try {
                socket = server.accept();
                // BufferedInputStream bIn=new BufferedInputStream(socket.getInputStream());
                BufferedOutputStream bOut=new BufferedOutputStream(socket.getOutputStream());
                BufferedWriter bWriter=new BufferedWriter(new OutputStreamWriter(bOut,"ASCII"));
                bWriter.write((new SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
                bWriter.flush();
                System.out.println(++i);
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }/* finally{ 
                if(socket!=null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }
            }*/
        }
    }

}

 

客户端:

public class Client {
    public static void main(String[] args) {

        InetSocketAddress address = null;
        address = new InetSocketAddress("127.0.0.1", 8080);

        int i = 0;
        while (true) {
            Socket socket = null;
            try {
                socket = new Socket();
                socket.connect(address);
                BufferedInputStream bIn = new BufferedInputStream(socket.getInputStream());
                int c;
                while ((c = bIn.read()) != -1) {
                    System.out.print((char) c);
                }
  相关解决方案