zoukankan      html  css  js  c++  java
  • web sockect的练习

    客户端

     public static void main(String[] args) {
    		Socket sk = null;
    		OutputStream os = null;
    		try {
    			InetAddress ip = InetAddress.getByName("127.0.0.1");
    			int port = 9999;
    		    sk=  new Socket(ip, port);
    		    
    		    os = sk.getOutputStream();
    		    os.write("呵呵呵呵呵呵!".getBytes());
    			
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
    			if(os!=null) {
    				try {
    					os.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			
    			if(sk!=null) {
    				try {
    					sk.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    
    

    服务器

    public static void main(String[] args) {
    		ServerSocket ss = null;
    		ByteArrayOutputStream Bao = null;
    		Socket socket = null;
    		InputStream is = null;
    		try {
    			ss = new ServerSocket(9999);
    			socket = ss.accept();
    			System.out.println("123456");
    			System.out.println("一个客户端已经建立连接");
    			is = socket.getInputStream();
    		    Bao = new ByteArrayOutputStream();
    		    byte[] buffer = new byte[1024];
    		    int len;
    		    while((len=is.read(buffer))!=-1) {
    		    	Bao.write(buffer,0,len);
    		    }
    			System.out.println(Bao.toString());
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}finally {
    			if(Bao!=null) {
    				try {
    					Bao.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			if(is!=null) {
    				try {
    					is.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			
    			if(socket!=null) {
    				try {
    					socket.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			
    			if(ss!=null) {
    				try {
    					ss.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    
  • 相关阅读:
    BUAA 软工 | 从计算机技术中探索艺术之路
    好好编程BUAA_SE(组/团队) Scrum Meeting 博客汇总
    beta事后分析
    Beta阶段项目展示
    Beta阶段测试报告
    Beta版本发布计划
    Beta阶段 第十次Scrum Meeting
    Beta阶段 第九次Scrum Meeting
    Beta阶段 第八次Scrum Meeting
    Beta阶段 第七次Scrum Meeting
  • 原文地址:https://www.cnblogs.com/wailaifeike/p/15407624.html
Copyright © 2011-2022 走看看