首页 > 代码库 > ServerSocket和Socket

ServerSocket和Socket

前言

      用ServerSocket和Socket做了个Server、Client通信的demo,以及学习下在这个demo过程中用到java.net、java.io包下几个常用的类。

 

Server

import java.net.*;import java.io.*;public class HttpServer{        public static void main(String[] args){        new HttpServer().start();    }        private ServerSocket serversocket=null;        public HttpServer(){        try{            serversocket=new ServerSocket(5000);//监听客户端端口5000的socket请求            System.out.println("服务器启动");        }catch(IOException e){            e.printStackTrace();        }    }    public void start(){        Socket socket=null;        while(true){            try{                socket=serversocket.accept(); //接受客户端请求socket                System.out.println("address:"+socket.getInetAddress()+":"+socket.getLocalPort());                                OutputStream os =socket.getOutputStream();                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));                //向客户端发送一条消息                bw.write("测试服务器通信\n");                bw.flush();            }catch(IOException e){                e.printStackTrace();                System.out.println("连接断开");            }finally{                try{                    if(socket !=null){                        socket.close();                    }                }catch(IOException e){                                    }            }        }    }}

Client

import java.net.*;import java.io.*;public class Client{        public static void main(String[] args){        Socket socket=null;        try{            socket =new Socket("127.0.0.1",5000);                                    InputStream is =socket.getInputStream();            InputStreamReader isr=new InputStreamReader(is);            BufferedReader br =new BufferedReader (isr);            String mess=br.readLine();                        System.out.println("mess:"+mess);        }catch(IOException e){            e.printStackTrace();        }finally{            try{                if(socket !=null){                    socket.close();                }            }catch(IOException e){                            }        }            }    }

 总结

     java.net包内几个常用的类: 

         ServerSocket、

         Socket、

         OutputStream、InputStream、

     InputStreamReader、OutputStreamWriter、

     BufferedReader、BufferedWriter、 

         InetAddress、

        

         

        

 

ServerSocket和Socket