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();
    				}
    			}
    		}
    	}
    
  • 相关阅读:
    根据地球上两个坐标点,计算出距离
    判断一个日期距离今天是不是过了指定的天数
    二维码
    修改、删除 触发器
    sql server 数据加密
    C#下载apk文件
    java 判断一个字符串是否包含某个字符串中的字符
    CenterOS 设置静态IP
    VMware 克隆 CenterOS 虚拟机
    VMware 安装CenterOS
  • 原文地址:https://www.cnblogs.com/wailaifeike/p/15407624.html
Copyright © 2011-2022 走看看