In this paper, the use of optimal control techniques for improving the energy absorption by a wave-energy converter (WEC) is investigated. A mathematical model is developed for a floating body, which is exposed to an irregular incident wave, and is moving relative to a fixed reference. This model includes a control force from the power take-off and control machinery, and a friction force which restricts the oscillation amplitude. This force models end-stop devices, which are necessary to protect the machinery. An optimal control strategy is determined, based on variations of a Lagrange functional. This gives a set of adjoint equations in addition to the state equations, as a necessary condition for optimum. An algorithm is given for solving the problem numerically by iteration, based on a gradient method. It is shown that the optimal motion in a sinusoidal wave is not sinusoidal when the excursion is constrained. Instead, the motion should be stopped in certain intervals. In irregular waves the constrained solution is close to the unconstrained solution when the excursion is small. Moreover, the timings of the extrema and of the zero crossings agree fairly well. When the excursion is constrained, the mean output power is reduced compared to the unconstrained case, but the ratio between the output energy and the total energy passing through the machinery is increased. This means that the conversion efficiency of the machinery is less critical.