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();
				}
			}
		}
	}
posted @ 2021-10-14 17:30  小猫妮  阅读(28)  评论(0编辑  收藏  举报