• java socket的简单模型


    服务器端代码:

    /**
    *
    * @author:李星星
    * @date:Dec 14, 2010
    */
    package com.lixx;

    import java.io.BufferedReader;
    import java.net.ServerSocket;

    public class SocketServer  extends Thread{

     private java.net.ServerSocket ss;   
        private java.net.Socket s;   
        @Override   
        public void run() {   
            try{   
                while(true){   
                    this.s=this.ss.accept();   
                    java.io.BufferedReader reader =   
                        new BufferedReader(   
                                new java.io.InputStreamReader(   
                                        s.getInputStream()));   
                    String str=reader.readLine();   
                    System.out.println("开始接受数据:");   
                    while(str!=null){   
                        System.out.println("读了一行");   
                        System.out.println(str);   
                        str=reader.readLine();   
                    }   
                    reader.close();   
                    this.s.close();   
                }   
            }catch(Exception ex){   
                ex.printStackTrace();   
            }   
        }   
        public SocketServer(int port){   
            try{   
                System.out.println("服务端启动.......");   
                this.ss=new ServerSocket(port);   
            }catch(Exception ex){   
                ex.printStackTrace();   
            }   
        }   
        public static void main(String[] args){   
            Thread t=new SocketServer(8888);   
            t.start();   
        }   
    }

    客户端代码:

    /**
    *
    * @author:李星星
    * @date:Dec 14, 2010
    */
    package com.lixx;

    import java.io.BufferedReader;

    public class SocketClient {

     public static void main(String[] args)throws Exception {   
            java.net.Socket s=new java.net.Socket("127.0.0.1",8888);   
            java.io.BufferedWriter out=new java.io.BufferedWriter(   
                    new java.io.OutputStreamWriter(   
                            new java.io.BufferedOutputStream(s.getOutputStream())));   
               
            java.io.BufferedReader reader=new BufferedReader(   
                    new java.io.InputStreamReader(System.in));   
               
            String str=reader.readLine();   
            while(!"exit".equals(str)){   
                out.write(str + "\n");   
                out.flush();   
                str=reader.readLine();   
            }   
            reader.close();   
            out.close();   
        }   
    }

  • 相关阅读:
    #背包#nssl 1488 上升子序列
    #环#nssl 1487 图
    #分治#JZOJ 4211 送你一颗圣诞树
    #概率,dp#JZOJ 4212 我想大声告诉你
    #并查集#JZOJ 4223 旅游
    #dp#nssl 1478 题
    #对顶堆#nssl 1477 赛
    #线段树,离散#nssl 1476 联
    #折半搜索,状压dp#nssl 1471 Y
    #并查集,线性筛#nssl 1470 X
  • 原文地址:https://www.cnblogs.com/xinzhuangzi/p/4100487.html
Copyright © 2020-2023  润新知