用ServerSocket和Socket做了个Server、Client通信的demo,以及学习下在这个demo过程中用到java.net、java.io包下几个常用的类。
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){ } } } } }
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、
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。