博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java网络编程01
阅读量:6551 次
发布时间:2019-06-24

本文共 9510 字,大约阅读时间需要 31 分钟。

  hot3.png

/简单版public static void main(String[] args) {        /*客户端通过Socket链接服务端*/        Socket s=null;        try {            s=new Socket("127.0.0.1",5858);            PrintWriter out=new PrintWriter(s.getOutputStream(),true);            out.println("hello1!");                        BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));            String str=br.readLine();            System.out.println(str);        }catch(UnknownHostException e){            e.printStackTrace();        }catch (Exception e) {            e.printStackTrace();        }finally{            try {                if(s!=null) s.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }        /*java网络编程步骤:     * 1.建立服务端和客户端     * 2.实现服务端     * 3.在服务器端接收客户端的链接     * 4.客户端与服务端进行通信*/    public static void main(String[] args) {        /*创建服务端就是就是创建服务端Socket,Socket注意需要关闭         * */        ServerSocket ss=null;        Socket s=null;        try {            ss=new ServerSocket(5858);//端口号不小于1024(系统保留),最大65355            System.out.println("Server is run!");            while(true){//服务端不能停止,死循环                try {                    s=ss.accept();    //接收客户端的请求                    String name=s.getInetAddress().getHostAddress()+":"+s.getPort();                    //System.out.println(s.getInetAddress()+":"+s.getPort()+"\thave Connected Server!");                    BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));                    String str=br.readLine();                    System.out.println(name+":"+str);                                        PrintWriter out=new PrintWriter(s.getOutputStream(),true);                    out.println("have receive clent info!");                } finally{                    if(s!=null){                        s.close();                        System.out.println(s+"out line");                    }                }            }        } catch (IOException e) {            e.printStackTrace();        }    }        /    public static void main(String[] args) {        Socket s=null;        BufferedReader sbr=null;        try {            s=new Socket("127.0.0.1",5858);            sbr=new BufferedReader(new InputStreamReader(System.in));            PrintWriter out=new PrintWriter(s.getOutputStream(),true);            BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));            String str=null;            while((str=sbr.readLine())!=null){                out.println(str);                String rs=br.readLine();                if(rs.equalsIgnoreCase("disconnected")){                    break;                }                System.out.println(rs);            }        } catch (UnknownHostException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(s!=null) s.close();            } catch (IOException e) {                e.printStackTrace();            }            try {                if(sbr!=null) sbr.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }        public static void main(String[] args) {        ServerSocket ss=null;        Socket s=null;        try {            ss=new ServerSocket(5858);            System.out.println("Server is run succseful");            try {                while(true){                    s=ss.accept();                    String name=s.getInetAddress().getHostAddress()+":"+s.getPort();                    System.out.println(name+" has connected");                    BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));                    PrintWriter out=new PrintWriter(s.getOutputStream(),true);                    String str=null;                    while((str=br.readLine())!=null){                        if(str.equalsIgnoreCase("quit")){//关闭释放资源                            out.println("disconnected");                            break;                        }                        System.out.println(name+":"+str);                        out.println(str);                    }                    System.out.println(name+"is out line");                }                            } catch (IOException e) {                e.printStackTrace();            }finally{                if(s!=null) s.close();                                }        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(ss!=null) ss.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }        ///支持启动    public class Client {    private Socket s;    private BufferedReader br;    private PrintWriter out;    private boolean flag=true;    public static void main(String[] args) {        new Client().startup();    }         public void startup(){        BufferedReader sbr=null;        try {            s=new Socket("127.0.0.1",5858);            sbr=new BufferedReader(new InputStreamReader(System.in));            PrintWriter out=new PrintWriter(s.getOutputStream(),true);            br=new BufferedReader(new InputStreamReader(s.getInputStream()));            out.println("hello");            new Thread(new ClientThread()).start();            String str=null;            while(flag&&(str=sbr.readLine())!=null){//问题:假如客户端不输入内容,就无法获取服务端内容,需要写入线程                out.println(str);                            }        } catch (UnknownHostException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(s!=null) s.close();            } catch (IOException e) {                e.printStackTrace();            }            try {                if(sbr!=null) sbr.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }        private void receive(){        try {            String rs=br.readLine();            if(rs.equalsIgnoreCase("disconnected")){                flag=false;                System.out.println("点击回车退出");            }            System.out.println(rs);        } catch (IOException e) {            e.printStackTrace();        }    }        private class ClientThread implements Runnable{        @Override        public void run() {            while(true){                if(!flag){                    break;                }                    receive();            }        }    }        server.java    private List
 clients=null;//存储连接的客户端    public static void main(String[] args) {        new Server().stratup();    }        private void stratup(){        ServerSocket ss=null;        Socket s=null;        String name=null;                try {            ss=new ServerSocket(5858);            clients=new ArrayList
();            System.out.println("Server is run succseful");                        while(true){                s=ss.accept();                ServerThread st=new ServerThread(s);                new Thread(st).start();            }                    } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(ss!=null) ss.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }         private class ServerThread implements Runnable{        private Socket s;        private BufferedReader br;        private PrintWriter out;        private String name;        boolean flag=true;                public ServerThread(Socket s) throws IOException{            this.s=s;                br=new BufferedReader(new InputStreamReader(s.getInputStream()));                out=new PrintWriter(s.getOutputStream(),true);                String str=br.readLine();                name=str+"["+s.getInetAddress().getHostAddress()+":"+s.getPort()+"]";                //System.out.println(name+" has connected");                clients.add(this);//每一个客户端连接就加入List中                send(name+"上线了");//通知其他人新人上线了        }                private void send(String msg){            for(ServerThread st:clients){                st.out.println(msg);            }        }        private void receive() throws IOException{//抛出异常,留给下一级捕获            String str=null;            while((str=br.readLine())!=null){                if(str.equalsIgnoreCase("quit")){//关闭释放资源                    this.stop();                                        out.println("disconnected");                    break;                }                System.out.println(name+":"+str);                send(name+":"+str);//群发            }            System.out.println(name+"is out line");        }                public void stop(){            clients.remove(this);            System.out.println(name+"is out line");            flag=false;            send(name+"已经下线了");        }        @Override        public void run(){                    try {                while(true){                    if(!flag) break;                    receive();                }            }catch (SocketException e) {                stop();            } catch (IOException e) {                e.printStackTrace();            }finally{                try {                    if(s!=null) s.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }

转载于:https://my.oschina.net/686991/blog/509109

你可能感兴趣的文章
轻松入门腾讯云存储系列一:对象存储COS的基本功能详解
查看>>
[译] 如何取消你的 Promise?
查看>>
OkHttp 知识梳理(3) OkHttp 之缓存基础
查看>>
[手把手教程][第二季]java 后端博客系统文章系统——No1
查看>>
从intrinsicContentSize到自动调整布局self-sizing
查看>>
重构并没有你想象的那么简单
查看>>
React Native填坑之旅--Stateless组件
查看>>
未来的.NET之多重继承
查看>>
为什么html里面的onclick函数后面要加(),而js里面不需要?
查看>>
LinkedIn庄振运:从国家部委公务员到硅谷系统性能专家,创新是唯一主旋律
查看>>
用户超5亿,三年投10亿,开发者如何抢滩支付宝小程序蓝海?
查看>>
NettyClient端调用remote service的方式
查看>>
spring-security详解
查看>>
使用python制作时间戳转换工具
查看>>
Drools实战系列(三)之eclipse创建工程
查看>>
Android利用Cookie实现码源登录效果
查看>>
****timeago.js插件:jquery实现几分钟前、几小时前、几天前等时间差显示效果的代码实例...
查看>>
我常用的命令
查看>>
tengine+tomcat+php安装
查看>>
第 45 章 HyperDex
查看>>