To realize the accurate control of water hammer in pipes by valve stroking, based on basic differential equations of water hammer subjected to initial and boundary conditions, the traveling solution of wave equations in finite region was applied to the linear water hammer problem. With the given velocity function at the valve and the introduction of curve integration independent of integral path, the exact analytic solution of dimensionless water hammer pressure was obtained in the course of valve closing. Based on the definition of eigen wave height, optimal eigen wave height and observation time, the control goal of water hammer pressure and the judgment rule of the optimal eigen wave height were determined, then the optimal velocity function in the calculated example was derived, which can reduce the water hammer pressure maximally. According to this function, a valve closing program was set, and the optimal control of water hammer could be realized.