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();
    				}
    			}
    		}
    	}
    
  • 相关阅读:
    JAVA基础(十六)Super关键字
    JAVA基础(十五)this关键字
    JAVA基础(十四2.0)
    JAVA基础(十三)多态
    JAVA基础(十二)抽象类与接口
    git基本使用
    vuetify中treeview部分属性梳理
    vuetify初次使用心得
    react-常见面试题
    maven中profile的使用
  • 原文地址:https://www.cnblogs.com/wailaifeike/p/15407624.html
Copyright © 2011-2022 走看看